qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
sequence
response
stringlengths
0
115k
11,568,187
I have the following tables: ``` tweets retweets ----------------- ---------------- user_id retweets user_id (etc...) ----------------- ---------------- 1 0 1 2 0 1 1 2 2 ``` I want to count the number of retweets per user and update tweets.retweets accordingly: ``` UPDATE users SET retweets = ( SELECT COUNT(*) FROM retweets WHERE retweets.user_id = users.user_id ) ``` I have been running this query two times, but it times out (on tables that are not that large). Is my query wring? Also see the SQL Fiddle (although it apparently doesn't allow `UPDATE` statements): <http://www.sqlfiddle.com/#!2/f591e/1>
2012/07/19
[ "https://Stackoverflow.com/questions/11568187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/330271/" ]
This solution should be much faster than using subqueries for getting the count of tweets of each user (your correlated subquery will execute for ***each*** user): ``` UPDATE users a LEFT JOIN ( SELECT user_id, COUNT(1) AS retweet_count FROM retweets GROUP BY user_id ) b ON a.user_id = b.user_id SET a.retweets = COALESCE(b.retweet_count, 0) ```
3,826
I'm designing an Arduino style board with built-in LEDs for several of the pins. To simplify assembly of the board and save on components, I was wondering whether it would be safe for those LEDs to share a single resistor, as in this diagram: ![schematic](https://i.stack.imgur.com/jWXVT.png) Obviously, the power dissipated through the resistor (3mA per pin @ 3V) is not a real problem. The reason I was hesitating is that LEDs in a parallel configuration should not share resistors, but is it safe to think that separate microcontroller pins don't count as a common anode, even if both pins are high?
2014/08/17
[ "https://arduino.stackexchange.com/questions/3826", "https://arduino.stackexchange.com", "https://arduino.stackexchange.com/users/353/" ]
> > **Can** two LEDs attached to different pins share their resistor? > > > * **can** : yes * **should** : probably not Your resistor act here as a current limiter, say to *3mA* If you light one LED at a time, you give 3mA to *that* LED If you light 2 LEDs, you give 3mA for both of them (more of less 1.5mA each) If you light 3 LEDs, you give 3mA for all of them (*on average* 1mA each) Things are even a little bit more subtle, as different LED might have different forward voltage, so one LED might very well drain 10% more current than an other. As "Amps made LED bright", less Amp is less light. On LED light with that setup will give "full light on", and more LED you add, less would bright each one. --- As an edit to that answer, there is one case I might consider that arrangement for "multi-LED lighting". This is if you are [multiplexing your LEDs](http://en.wikipedia.org/wiki/Multiplexed_display) That is lighting only one at a time, but cycling fast enough from one LED to the next so that the human eye would *see* them all lit at once.
2,935,229
I am considering generating a unique form token and storing it in a session, and embedding it as a hidden input in my forms. Could I make this work for pages containing multiple forms, is it still safe to use the same token for each form? I'm looking to detect bot requests on my website, can these form tokens really safely replace CAPTCHAs?
2010/05/29
[ "https://Stackoverflow.com/questions/2935229", "https://Stackoverflow.com", "https://Stackoverflow.com/users/138251/" ]
Apache is one of the most hardened software projects on the face of the planet. Finding a vulnerability in Apache's HTTPD would be no small feat and I recommend cutting your teeth on some easier prey. By comparison it is more common to see vulnerabilities in other HTTPDs such as this one in [Nginx](http://www.securityfocus.com/archive/1/511556) that I saw today (no joke). There have been other source code disclosure vulnerablites that are very similar, I would look at [this](http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2010-0642) and here is [another](http://web.nvd.nist.gov/view/vuln/detail?vulnId=CVE-2010-1587). [lhttpd](http://sourceforge.net/projects/lhttpd/) has been abandoned on sf.net for almost a decade and there are known buffer overflows that affect it, which makes it a fun application to test. When attacking a project you should look at what kind of vulnerabilities have been found in the past. Its likely that programmers will make the same mistakes again and again and often there are patterns that emerge. By following these patterns you can find more flaws. You should try searching vulnerablites databases such as [Nist's search for CVEs](http://web.nvd.nist.gov/view/vuln/search). One thing that you will see is that apache modules are most commonly compromised. A project like Apache has been heavily fuzzed. There are fuzzing frameworks such as [Peach](http://peachfuzzer.com/). Peach helps with fuzzing in many ways, one way it can help you is by giving you some nasty test data to work with. Fuzzing is not a very good approach for mature projects, if you go this route I would target [apache modules](http://sourceforge.net/search/?type_of_search=soft&words=%2Bapache+%2Bmod&search=Search) with as few downloads as possible. (Warning projects with *really* low downloads might be broken or difficult to install.) When a company is worried about secuirty often they pay a lot of money for an automated source analysis tool such as Coverity. The Department Of Homeland Security gave Coverity a ton of money to test open source projects and [Apache is one of them](http://scan.coverity.com/rung1.html). I can tell you first hand that I have found [a buffer overflow](http://www.milw0rm.com/exploits/8470) with fuzzing that Coverity didn't pick up. Coverity and other source code analysis tools like the [open source Rats](http://www.fortify.com/security-resources/rats.jsp) will produce a lot of false positives and false negatives, but they do help narrow down the problems that affect a code base. (When i first ran RATS on the Linux kernel I nearly fell out of my chair because my screen listed thousands of calls to strcpy() and strcat(), but when i dug into the code all of the calls where working with static text, which is safe.) Vulnerability resarch an exploit development is [a lot of fun](http://www.milw0rm.com/author/677). I recommend exploiting PHP/MySQL applications and exploring [The Whitebox](http://code.google.com/p/thewhitebox/). This project is important because it shows that there are some real world vulnerabilities that cannot be found unless you read though the code line by line manually. It also has real world applications (a blog and a shop) that are very vulnerable to attack. In fact both of these applications where abandoned due to security problems. A web application fuzzer like [Wapiti](http://wapiti.sourceforge.net/) or acuentix will rape these applications and ones like it. There is a trick with the blog. A fresh install isn't vulnerable to much. You have to use the application a bit, try logging in as an admin, create a blog entry and then scan it. When testing a web application application for sql injection make sure that error reporting is turned on. In php you can set `display_errors=On` in your php.ini. Good Luck!
425,725
With the `auth-user-pass filename` option is it possible to create a plain text file with username and passphrase. Is it possible to have the username and passphrase directly in the client.conf?
2012/09/09
[ "https://serverfault.com/questions/425725", "https://serverfault.com", "https://serverfault.com/users/34187/" ]
Not without recompiling `openvpn`. It's made this way to discourage putting them there. If you want to have automatic VPN channel negotiation you really should use certificates and private keys. There should be an `easy-rsa` directory in documentation with scripts that will make it easier to set up single-purpose CA. If you can't reconfigure the server (because you're not its administrator) then you really shouldn't keep your passwords in plain-text files...
29,786,548
I'm working in JNA to call C functions, and I'm quite used to the Java `read()` function which reads a single byte. Is there a way to do this in C without declaring a buffer?
2015/04/22
[ "https://Stackoverflow.com/questions/29786548", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3618509/" ]
``` char oneByte; int r=read(fd, &oneByte, 1); ``` Yes, should work.
18,263,585
Here is a **[fiddle](http://jsfiddle.net/zCFr5/)**. I'm trying to create a countdown object that uses [moment.js](http://momentjs.com/) (a plugin that I prefer over using Date()) ``` var Countdown = function(endDate) { this.endMoment = moment(endDate); this.updateCountdown = function() { var currentMoment, thisDiff; currentMoment = moment(); thisDiff = (this.endMoment).diff(currentMoment, "seconds"); if (thisDiff > 0) console.log(thisDiff); else { clearInterval(this.interval); console.log("over"); } } this.interval = setInterval(this.updateCountdown(), 1000); } ``` I then create a instance of the countdown like so: ``` var countdown = new Countdown("January 1, 2014 00:00:00"); ``` However the function only seems to run one time. Any ideas? Should I be using setTimeout() instead?
2013/08/15
[ "https://Stackoverflow.com/questions/18263585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1179207/" ]
You should pass a *reference* to function, not the result of its execution. Also, you need some additional "magic" to call a method this way. ``` var me = this; this.interval = setInterval(function () { me.updateCountdown(); }, 1000); ```
41,151,365
My stored procedure always returns a null value when I try to select it. I did some research and I have to specify somewhere OUTPUT. Not sure where or how to do that. ``` delimiter $$ Create Procedure ClientPurchases (IN idClient INT, outClientAvgPurchases DECIMAL (4,2)) BEGIN DECLARE PurchasesAvg DECIMAL(4,2) ; set PurchasesAvg= (SELECT AVG(PurchaseAmount) FROM Purchase inner join Client on idClient=Client_idClient); SET outClientAvgPurchases= PurchasesAvg; END$$ CALL ClientPurchase(3, @purchase ); SELECT @purchase as 'Purchase Total'; ```
2016/12/14
[ "https://Stackoverflow.com/questions/41151365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6221064/" ]
You simply missed to add the `/s` option to the `dir` command: ``` @echo off setlocal EnableExtensions EnableDelayedExpansion set "FOLDER=" & set /P FOLDER="" for /f "tokens=3" %%A in (' dir /S /A:-D /-C "!FOLDER!" ') do ( set "SIZE=!FREE!" set "FREE=%%A" ) echo free space is %free% bytes echo size is %size% bytes endlocal ```
35,137,768
How can I try sending a post request to a Laravel app with Postman? Normally Laravel has a `csrf_token` that we have to pass with a POST/PUT request. How can I get and send this value in Postman? Is it even possible *without turning off* the CSRF protection?
2016/02/01
[ "https://Stackoverflow.com/questions/35137768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3048381/" ]
Edit: ----- Ah wait, I misread the question. You want to do it without turning off the CSRF protection? Like Bharat Geleda said: You can make a route that returns only the token and manually copy it in a `_token` field in postman. But I would recommend excluding your api calls from the CSRF protection like below, and addin some sort of API authentication later. *Which version of laravel are you running?* Laravel 5.2 and up: ------------------- Since 5.2 the CSRF token is only required on routes with `web` middleware. So put your api routes outside the group with `web` middleware. See the "The Default Routes File" heading in the [documentation](https://laravel.com/docs/5.2/routing#basic-routing) for more info. Laravel 5.1 and 5.2: -------------------- You can exclude routes which should not have CSRF protection in the `VerifyCsrfToken` middleware like this: ``` class VerifyCsrfToken extends BaseVerifier { /** * The URIs that should be excluded from CSRF verification. * * @var array */ protected $except = [ 'api/*', ]; } ``` See the "Excluding URIs From CSRF Protection" heading [documentation](https://laravel.com/docs/5.1/routing#csrf-excluding-uris) for more info.
20,780,766
Basically i want to create translate animation but for some reason i cannot use TranslateAnimation class. Anyway this is my code main.xml ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/layout" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <ImageView android:id="@+id/image" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher"/> </RelativeLayout> ``` MainActivity.java ``` package com.test2; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.RelativeLayout; import android.widget.RelativeLayout.LayoutParams; import android.widget.ImageView; public class MainActivity extends Activity { private RelativeLayout layout; private ImageView image; private LayoutParams imageParams; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); layout = (RelativeLayout) findViewById(R.id.layout); image = (ImageView) findViewById(R.id.image); imageParams = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); image.setLayoutParams(imageParams); layout.setOnClickListener(new ClickHandler()); } class ClickHandler implements OnClickListener { public void onClick(View view) { // This is the animation part for (int i = 0; i < 100; i++) { imageParams.leftMargin = i; image.setLayoutParams(imageParams); // repaint() in java try { Thread.sleep(100); } catch (Exception e) { } } } } } ``` My problem is I need to do repaint() before using Thread.sleep otherwise the animation will not work and the object will just move to its final position. I've tried invalidate, requestLayout, requestDrawableState but none works. Any suggestion? EDIT: main.xml ``` <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/layout" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> </RelativeLayout> ``` MainActivity.java ``` public class MainActivity extends Activity { private RelativeLayout layout; private ImageView image; private LayoutParams imageParams; private Timer timer; private int i; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); layout = (RelativeLayout) findViewById(R.id.layout); image = new ImageView(this); image.setImageResource(R.drawable.ic_launcher); imageParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); image.setLayoutParams(imageParams); layout.addView(image); i = 0; timer = new Timer(); runOnUiThread ( new Runnable() { public void run() { timer.scheduleAtFixedRate ( new TimerTask() { @Override public void run() { imageParams.leftMargin = i; image.setLayoutParams(imageParams); i++; if (i == 15) { timer.cancel(); timer.purge(); } } }, 0, 100 ); } } ); } } ```
2013/12/26
[ "https://Stackoverflow.com/questions/20780766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3135962/" ]
``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity" > </RelativeLayout> package com.example.example; import java.util.Timer; import java.util.TimerTask; import android.os.Bundle; import android.widget.ImageView; import android.widget.RelativeLayout; import android.app.Activity; public class MainActivity extends Activity { ImageView imageView; RelativeLayout.LayoutParams params; int i=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); imageView=new ImageView(this); RelativeLayout main=(RelativeLayout)findViewById(R.id.main); params=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT); imageView.setBackgroundResource(R.drawable.ic_launcher); imageView.setLayoutParams(params); main.addView(imageView); final Timer timer=new Timer(); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { runOnUiThread(new Runnable() { public void run() { params.leftMargin=i; imageView.setLayoutParams(params); i++; if(i>=100){ timer.cancel(); timer.purge(); } } }); } }, 0, 100); } } ```
70,507
I am hiring a PHP developer to build me a website. Their rate is 70$ an hour. He seems to have a good portfolio and experience. How do I know that I get a good website that is scalable and easy to maintain? Do I ask them to give me code samples so I can review it (I am a programmer but I did not do much PHP)? What are good credentials for a PHP developer? experience with Drupal? LAMP?
2011/04/22
[ "https://softwareengineering.stackexchange.com/questions/70507", "https://softwareengineering.stackexchange.com", "https://softwareengineering.stackexchange.com/users/23599/" ]
It is the same thing as when you go to the mechanic? How do you know that they are actually fixing something and not causing more problems for repeat business? The answer lies in asking for references. See if he will give you the names of people he's done work for and then get into contact with them. If you do not know PHP then asking for code samples won't do you much good.
15,452,832
**Table1** ``` HolId 1 Package17 2,1,5 2 Package13 5,4,3 ``` **Table 2** ``` HolId1 1 New Years Day 2013-01-01 00:00:00.000 2 Republic Day 2013-01-26 00:00:00.000 3 Holi 2013-04-27 00:00:00.000 4 Memorial Day 2013-05-27 00:00:00.000 5 US Independence 2013-07-04 00:00:00.000 7 Labour Day 2013-09-02 00:00:00.000 ``` I want to display data like below ``` HolId HolId1 Package17 2 2 Republic Day 2013-01-01 00:00:00.000 Package17 1 1 New Years Day 2013-04-27 00:00:00.000 Package17 5 5 US Independence 2013-05-27 00:00:00.000 Package13 5 5 US Independence 2013-07-04 00:00:00.000 Package13 4 4 Memorial Day 2013-05-27 00:00:00.000 Package13 3 3 Holi 2013-04-27 00:00:00.000 ``` My grid will be displayed as follows which i have figured out ``` Package17 Republic Day 2013-01-01 00:00:00.000 New Years Day 2013-04-27 00:00:00.000 US Independence 2013-05-27 00:00:00.000 Package13 US Independence 2013-07-04 00:00:00.000 Memorial Day 2013-05-27 00:00:00.000 Holi 2013-04-27 00:00:00.000 ```
2013/03/16
[ "https://Stackoverflow.com/questions/15452832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/823528/" ]
This is solution for `MySQL`: ``` SELECT T1.Pkg, T2.* FROM Table2 T2 JOIN Table1 T1 ON FIND_IN_SET(T2.HolID1, T1.HolID) ``` **[SQL FIDDLE DEMO](http://sqlfiddle.com/#!2/30c3c/4)** and this is for `SQL SERVER` ``` SELECT T1.Pkg, T2.* FROM Table2 T2 JOIN Table1 T1 ON CHARINDEX(CAST(T2.HolID1 as varchar), T1.HolID) > 0 ``` **[SQL FIDDLE DEMO](http://sqlfiddle.com/#!3/314dd/1)**
48,299,218
I've written the following function in the spider to scrape info in a website. I've enabled the Image pipelines to even scrape the image along with the associated scraped data. With this piece of code i'm able to yield either the images or the `scraped_data` (which is commented in the last second line). Can anyone please help me with this as how can i yield both the images and the `scraped_info`? ``` def parse_info(self, response): url = response.url title = str(response.xpath('//*[@dataitem="itemTitle"]/text()').extract_first()) img_url_1 = response.xpath("//img[@id='icImg']/@src").extract_first() scraped_info = { 'title' : title, } yield {'image_urls': [img_url_1]} ``` I've checked running this code for scraping images which was successful. Thus, there's no error in `settings.py` or `items.py`. I'm concerned about scraping the images with the scraped data together. Any help?
2018/01/17
[ "https://Stackoverflow.com/questions/48299218", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4393262/" ]
As per [documentation](https://doc.scrapy.org/en/latest/topics/media-pipeline.html#using-the-images-pipeline) to Image Pipeline, items that you yield have to contain field `image_urls` (as a list). The Image Pipeline will download the images and populate another field of the item - `images` - with information about downloaded images. Thus, you have to modify your code like this (showing only the relevant part): ``` def parse_info(self, response): item = response.meta.get('item') url=response.url title=str(response.xpath('//*[@id="itemTitle"]/text()').extract_first()) img_urls=response.xpath("//img[@id='icImg']/@src").extract() scraped_info = { 'url' : url, 'title' : title, 'image_urls' : img_urls } yield scraped_info ```
49,863,232
**Disclaimer: I'm really new to WPF.** After looking around online I've understood that the HttpClient should be used as a singleton, shared between windows in WPF. However, I can't seem to find a *clear* startup entry-point as you'd find in MVC (startup, duh!). ***Where should I instantiate my HttpClient, and how can I use it across multiple windows?*** Currently I have two windows; Login and MainWindow. Both really basic. Example: ``` public partial class Login : Window { public Login() { InitializeComponent(); } private void BtnLoginSubmit_Click(object sender, RoutedEventArgs e) { } } ``` --- In my App.xaml.cs I've instantiated a HttpClient object which I can access from my MainWindow: App.xaml.cs: ``` public partial class App : Application { public HttpClient httpClient { get; set; } } ``` MainWindow.xaml.cs: ``` public partial class MainWindow : Window { private static ObservableCollection<string> states; public static void Add(string state) { states.Add(state); } public MainWindow() { InitializeComponent(); ((App)Application.Current).httpClient = new HttpClient(); states = new ObservableCollection<string>(); states.Add("Initialized"); states.CollectionChanged += states_CollectionChanged; LblStates.ItemsSource = states; Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch); } static void SystemEvents_SessionSwitch(object sender, SessionSwitchEventArgs e) { if (e.Reason == SessionSwitchReason.SessionLock) { } MainWindow.Add(e.Reason.ToString()); } void states_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add) { LblStates.Items.Refresh(); } } } ```
2018/04/16
[ "https://Stackoverflow.com/questions/49863232", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5986941/" ]
The most basic approach would be to add a static class that holds a static instance of HttpClient. ``` internal static class HttpClientManager { public static HttpClient Client = InititializeHttpClient(); } ``` You can then reference the client from anywhere, like `HttpClientManager.HttpClient`.
32,084,741
Hey i want on my Page a Random BG everytime a User visit that Page. At the moment i simple use ``` <body background="./images/bgs/random/<?php echo rand(1,13); ?>.jpg"> ``` But now when a User logs in -> or a other Page Reload ... the Background changes too and thats a but ugly. So my Question is there a better way or a solve so that the bg is loading only once ? with sessions or something idk Every Answer is welcome thanks! :)
2015/08/19
[ "https://Stackoverflow.com/questions/32084741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5221267/" ]
Use a `$_SESSION`. Make sure that you use `session_start()` before any headers are sent. ``` <?php session_start(); if(!isset($_SESSION['background'])){ $_SESSION['background'] = rand(1,13); // now just use $_SESSION['background'] } ?> ```
12,113
What do you do when notes from a chord in the left hand overlap with notes from a melody in the right hand? Do you drop notes? Do you change notes in the chord? This is my biggest frustration right now trying to play from fake books.
2013/09/29
[ "https://music.stackexchange.com/questions/12113", "https://music.stackexchange.com", "https://music.stackexchange.com/users/7166/" ]
This kind of playing (reading from lead sheets/fake books) is inherently improvisatory, so the prevailing wisdom should always be **"do what sounds good"**. There are a billion ways to play any given chart in a fake book, so keep in mind that you're not looking for one right answer. If you're working on a specific voicing technique, then the first thing I might try would be to either drop the bass by an octave or raise the melody up by an octave, in order to give yourself some room to work with. You shouldn't "change notes" in the chord, but you could change the chord voicing, or leave out nonessential notes. As anyone will tell you, the most important notes in most jazz chords are the 3rd and the 7th, so as long as the voicing has some indication of that specific tension, you're probably okay. Case in point: a dominant 7th chord can be outlined in the space of a tritone: `F - G - B` (G7), so you do have the option of being very economical with your space. The voicing you mention, with chords in the left hand and melody in the right, isn't all that typical of solo jazz piano playing as far as I'm concerned. You'd see that in stride piano or when soloing over your own chords, certainly, but a lot more common would be to put just a bass note in the left hand, and chords in the right hand *that track the melody as the top note in the chord*. It's usually pretty hard to run into that kind of trouble when you're voicing that way, since you can have the bass note WAY far away from your melody and chords.
19,024,137
Iam very new in jquery. here is jquery from [smart wizard](https://github.com/mstratman/jQuery-Smart-Wizard/blob/master/README.md): ``` / Default Properties and Events $.fn.smartWizard.defaults = { selected: 0, // Selected Step, 0 = first step keyNavigation: true, // Enable/Disable key navigation(left and right keys are used if enabled) enableAllSteps: false, transitionEffect: 'fade', // Effect on navigation, none/fade/slide/slideleft contentURL:null, // content url, Enables Ajax content loading contentCache:true, // cache step contents, if false content is fetched always from ajax url cycleSteps: false, // cycle step navigation enableFinishButton: false, // make finish button enabled always hideButtonsOnDisabled: false, // when the previous/next/finish buttons are disabled, hide them instead? errorSteps:[], // Array Steps with errors labelNext:'Next', labelPrevious:'Previous', labelFinish:'Finish', noForwardJumping: false, ajaxType: "POST", onLeaveStep: null, // triggers when leaving a step onShowStep: null, // triggers when showing a step onFinish: null, // triggers when Finish button is clicked includeFinishButton : true // Add the finish button }; })(jQuery); <script type="text/javascript"> $(document).ready(function() { // Smart Wizard $('#wizard').smartWizard({ onLeaveStep: leaveAStepCallback, onFinish: onFinishCallback }); function leaveAStepCallback(obj, context) { debugger; alert("Leaving step " + context.fromStep + " to go to step " + context.toStep); return validateSteps(context.fromStep); // return false to stay on step and true to continue navigation } function onFinishCallback(objs, context) { debugger; if (validateAllSteps()) { $('form').submit(); } } // Your Step validation logic function validateSteps(stepnumber) { debugger; var isStepValid = true; // validate step 1 if (stepnumber == 1) { // Your step validation logic // set isStepValid = false if has errors } // ... } function validateAllSteps() { debugger; var isStepValid = true; // all step validation logic return isStepValid; } }); </script> ``` i need some functione for onFinish, where i can send request with many parameters. how to do it?
2013/09/26
[ "https://Stackoverflow.com/questions/19024137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/291120/" ]
First of all download the smartWizard.js from <https://github.com/mstratman/jQuery-Smart-Wizard> then add it in your workspace and give the reference in your html/jsp. ``` <script type="text/javascript" src="js/jquery.smartWizard-2.1.js"></script> ``` then, ``` <script type="text/javascript"> $(document).ready(function(){ // Smart Wizard $('#wizard').smartWizard(); //$('#range').colResizable(); function onFinishCallback(){ $('#wizard').smartWizard('showMessage','Finish Clicked'); } }); </script> ``` Then in the jquery.smartWizard-2.1.js search for onFinish, Just try giving alert and then whatever you want to add you can add it directly in the .js file.
91,568
I am trying to understand the sentence "Tom loves Jane with his whole being" without involving the word "with". Does the sentence "Tom loves Jane with his whole being" have the exact same meaning as "Tom's whole being loves Jane"?
2016/06/01
[ "https://ell.stackexchange.com/questions/91568", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/34511/" ]
**with his whole being** is a metaphor meaning completely and without reservations. It is similar in meaning to [wholeheartedly](http://dictionary.cambridge.org/dictionary/english/wholehearted?q=wholeheartedly), which means with (someone's) whole heart. The heart is a metaphor for the emotions, so wholeheartedly means with all of one's emotions. [being](http://www.collinsdictionary.com/dictionary/english/being) is what defines a person- their essence, personality, spirit, soul: the part that goes away when somebody dies. **with his whole being** means with every part of his personality. The following sentence might be a suitable way of explaining your original sentence: > > Everything that Tom thinks, says or does reflects his love for Jane. > > >
66,596,421
I have a parent entity called Player and two child entities called bat and ball. PK of Player entity is 'playerId', composite pk of ball is 'playerId(FK)' and 'ballColor', & composite pk of bat is 'playerId(FK)' and 'batColor' Note : player-to-bat is OneToOne and player-to-ball is OneToMany (unidirectional) ``` @Entity @Table(name = "player") public class Player implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name = "player_id") private Long playerId; @JsonManagedReference @OneToMany(mappedBy = "player", cascade = CascadeType.ALL, fetch = FetchType.LAZY) @Fetch(value=FetchMode.SELECT) private List<Ball> balls; @OneToOne(mappedBy = "player", cascade = CascadeType.ALL, fetch = FetchType.LAZY) @JsonManagedReference private Bat bat; // getters and setters } @Entity @Table(name = "bat") public class Bat implements Serializable { private static final long serialVersionUID = -114046508592L; @EmbeddedId private BatEmbeddedId batEmbeddedId = new BatEmbeddedId(); @MapsId("playerId") @OneToOne @JoinColumn(name = "bat_id", insertable = false, updatable = false) @JsonBackReference private Player player; // getters and setters for player field } @Entity @Table(name = "ball") public class Ball implements Serializable { private static final long serialVersionUID = -1108592L; @EmbeddedId private BallEmbeddedId ballEmbeddedId = new BallEmbeddedId(); @MapsId("playerId") @ManyToOne @JoinColumn(name = "ball_id", insertable = false, updatable = false) @JsonBackReference private Player player; // getters and setters for player field } @Embeddable public class BatEmbeddedId implements Serializable{ private static final long serialVersionUID = -91976886L; @Column(name = "player_id") private Long playerId; @Column(name = "bat_color") private String batColor; public BatEmbeddedId() {} public BatEmbeddedId(Long playerId, String batColor) { super(); this.playerId= playerId; this.batColor= batColor; } // getters and setters for all fields } @Embeddable public class BallEmbeddedId implements Serializable{ private static final long serialVersionUID = -91976889990L; @Column(name = "player_id") private Long playerId; @Column(name = "ball_color") private String ballColor; public BatEmbeddedId() {} public BatEmbeddedId(Long playerId, String ballColor) { super(); this.playerId= playerId; this.ballColor= ballColor; } // getters and setters for all fields } public interface PlayerRepository extends JpaRepository<Player, Long>, JpaSpecificationExecutor<Player> { Player findByPlayerId(Long playerId); } @Service public class myService{ @Autowired PlayerRepository playerRepository; // Save logic for player Player player = new Player(); BatEmbeddedId batEmId = new BatEmbeddedId(); //note i can't set the playerId here coz its not yet generated batEmId.setBatColor("white"); Bat bat = new Bat(); bat.setBatEmbeddedId(batEmId); bat.setPlayer(player); player.setBat(bat); // added bat to player object List<Ball> balls = new ArrayList<>(); BallEmbeddedId ballEmId1 = new BallEmbeddedId(); BallEmbeddedId ballEmId2 = new BallEmbeddedId(); ballEmId1.setBallColor("white"); ballEmId2.setBallColor("red"); Ball b1 = new Ball(); Ball b2 = new Ball(); b1.setBallEmbeddedId(ballEmId1); b2.setBallEmbeddedId(ballEmId2); balls.add(b1); balls.add(b2); //adding balls to player object player.setBalls(balls); //finally calling a save playerRepository.save(player); } ``` After running the above code am getting the following error : `org.springframework.dao.DataIntegrityViolationException: A different object with the same identifier value was already associated with the session` Am I doing something wrong in the save logic of these related entities ? Many thanks in advance!!!
2021/03/12
[ "https://Stackoverflow.com/questions/66596421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11370275/" ]
Try to correct your mapping like below: ```java @Entity @Table(name = "bat") public class Bat implements Serializable { // ... @EmbeddedId private BatEmbeddedId batEmbeddedId = new BatEmbeddedId(); @MapsId("playerId") @OneToOne @JoinColumn(name = "player_id") @JsonBackReference private Player player; // getters and setters for player field } @Embeddable public class BatEmbeddedId implements Serializable{ // ... // @Column annotation will be ignored as you use @MapsId("playerId") // The column name will be taken from the @JoinColumn(name = "player_id") annotation // @Column(name = "player_id") private Long playerId; @Column(name = "bat_color") private String batColor; public BatEmbeddedId() {} public BatEmbeddedId(Long playerId, String batColor) { // super() is redundant // super(); this.playerId= playerId; this.batColor= batColor; } // getters and setters for all fields // The primary key class must define equals and hashCode methods, // consistent with equality for the underlying database types to which the primary key is mapped. // see https://docs.jboss.org/hibernate/orm/5.4/userguide/html_single/Hibernate_User_Guide.html#identifiers-composite @Override public boolean equals(Object o) { if ( this == o ) return true; if ( o == null || getClass() != o.getClass() ) return false; BatEmbeddedId pk = (BatEmbeddedId) o; return Objects.equals( playerId, pk.playerId ) && Objects.equals( batColor, pk.batColor ); } @Override public int hashCode() { return Objects.hash( playerId, batColor ); } } @Entity @Table(name = "ball") public class Ball implements Serializable { // ... @EmbeddedId private BallEmbeddedId ballEmbeddedId = new BallEmbeddedId(); @MapsId("playerId") @ManyToOne @JoinColumn(name = "player_id") @JsonBackReference private Player player; // getters and setters for player field } @Embeddable public class BallEmbeddedId implements Serializable{ // ... // @Column(name = "player_id") private Long playerId; @Column(name = "ball_color") private String ballColor; public BatEmbeddedId() {} public BatEmbeddedId(Long playerId, String ballColor) { this.playerId= playerId; this.ballColor= ballColor; } // getters and setters for all fields // equals and hashCode } ```
66,502,452
Recently i worked on one project, where Angular is used as the front end framework and springboot is backend. Now i moved to .NET projects .I understood that Blazor supports two hosting models, client side hosting model and server side hosting model. Now i am going to start .NET project with blazor. I have created REST API for the project.Now i have to use Blazor in that project.Here my doubt comes. 1)Blazor web assembly is for front end (or) back end ? 2)Blazor Server app is for front end (or) back end?
2021/03/06
[ "https://Stackoverflow.com/questions/66502452", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14943292/" ]
Just a few words of explanation. In traditional web design, you have a server which assembles code using stuff the user's browser must not have access to: database searches, proprietary logic, files and so on. That's usually done with C#, PHP, etc. That's the back end. Front end is the stuff that can and IS done in the user's browser: changing text, collecting input, handling mouse events and so on. That's usually done with JavaScript. This is because JavaScript is safer to run on a browser-- it doesn't have access to your drives and so on. How web pages work is that you collect form information-- type in text, set the state of checkboxes, etc., then package ALL that information with a form submission to the server. The server then processes all that information, REBUILDS the entire page, and sends a whole, complete page back to the client's browser. It's a very big transaction. Blazor doesn't do that. Everything on a page can be individually updated at any time without sending large blocks of information back and forth. Every event on a page (button click and so on) can be sent as an individual event call to the server, and you can return either no changes (for example if you're just saving some info to a database), or by changing any or all the content on the page. In other words, there's not really a very meaningful distinction between front end anymore: the visible page is an expression of the current state of code, rather than a new object that gets rebuilt every time you click a button. And just to clarify, it's a very robust connection-- you can check the contents on a textbox in real time as you type each character, or you can send updates to the user while you grind through 20 file uploads: "Processing image 1/20" and so on.
65,608,535
I have an application that works as expected and I can insert/update the rows through application. But when I connect to my oracle database through SQL Developer and tried to run the UPDATE query, I get message that 1 row is updated. while the row is not updated. Also the user I used to connect oracle database is same for both Application and SQL Developer with having insert and update privileges. I feel a transparency Layer is implemented in oracle database that blocks the direct query execution. Can anyone knows how this feature is implemented or which oracle product is configured?
2021/01/07
[ "https://Stackoverflow.com/questions/65608535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8403256/" ]
In your template use the pre tag and json pipe, ```js <pre> {{ InstanceId | json }} </pre> ```
60,489,923
I've got dict with array like this ``` tests: test01: state: 'enabled' objects: - 'A111' - 'B111' test02: state: 'enabled' objects: - 'C222' - 'D222' test03: state: 'enabled' objects: - 'E333' - 'F333' ``` How to combine array "objects" together in one output? The result should be ``` "msg": "A111,B111,E333,F333,C222,D222" ```
2020/03/02
[ "https://Stackoverflow.com/questions/60489923", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4747256/" ]
Is this what you need ``` - debug: msg: "{{(tests.test01.objects,tests.test02.objects,tests.test03.objects)|flatten|join('\n')|replace('\n', ',')}}" ``` > > ok: [localhost] => { > "msg": "A111,B111,C222,D222,E333,F333" > } > > >
35,440,204
``` public class saeidactivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.saeid); Button btn=(Button) findViewById(R.id.saeidbtn1); TextView str=(TextView) findViewById(R.id.saeidtxtv1); btn.setOnClickListener(new OnClickListener(){ @Override public void onClick(View v) { str.setTextColor(0xFF00FF00); } }); } } ```
2016/02/16
[ "https://Stackoverflow.com/questions/35440204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5928886/" ]
You need to learn about OOP (Object Oriented Programming) in more detail. Perhaps search for Dependency Injection, or Exceptions. Also, you need to create a PHP script that accepts your ajax requests and calls the necessary functions or methods which should all be separated into their own files and in classes. This will separate the different data layers from each other (i.e. presentation, business logic, data). You should also invest some time in learning what MVC(Model View Controller) is about. This will help you understand the importance of the separation. For now, I will show you a quick solution to your problem. Lets imagine your file structure is all in the same directory as such: ``` |--- ajax_requests.php |--- Database.php |--- Functions.php |--- index.php ``` **index.php** is where your HTML /jQuery is located: ``` <!DOCTYPE html> <html> <head> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> <title>Admin check</title> <meta charset="UTF-8"> </head> <body> <script type='text/javascript'> $.ajax({ type: "post", url: "ajax_requests.php", data: {request: "get_grupy_json"}, success: function(result){ console.log(result); } }); </script> ``` Notice how we are using jQuery to make our Ajax request. We are making a `post` request to the file `ajax_requests.php` sending the `get_grupy_json` as our `request` parameter. No SQL queries should be present on your front-end views. **ajax\_requests.php** receives the request, gets the Database object and sends it to the Functions object, then it checks that the request exists as a method of the Functions class, if it does, it runs the method and turns the result as json (remember to add error checking on your own): ``` <?php if (!empty($_POST)) { $method = $_POST['request']; include 'Database.php'; include "Functions.php"; $db = new Database(); $functions = new Functions($db); if (method_exists($functions, $method)) { $data = $functions->$method(); header('Content-Type: application/json'); echo json_encode($data); } } ``` **Functions.php** ``` class Functions { private $db; public function __construct(Database $db) { $this->db = $db; } public function get_grupy_json() { $query = "SELECT * FROM `grupy`"; $result = $this->db->dataQuery($query); return $result->fetchAll(); } } ``` **Database.php** ``` class Database { private $conn = null; public function __construct() { try { $username = "root"; $password = "root"; $servername = "localhost"; $dbname = "test"; $this->conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password); $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (PDOException $e) { trigger_error("Error: " . $e->getMessage()); } } public function dataQuery($query, $params = array()) { try { $stmt = $this->conn->prepare($query); $stmt->execute($params); return $stmt; } catch (PDOException $e) { trigger_error("Error: " . $e->getMessage()); }; } } ``` This is a rough mockup of what i would do. I hope you get the idea of how it is all separated so that you can easily add features to your application as it grows.
894,646
I do not understand improper integrals. Is $$ \int\_1^e \frac{ \mathrm{dx}}{x(\ln x)^{1/2}}$$ an improper integral? Is $$ \int\_0^2 \frac{\mathrm{dx}}{x^2+6x+8}$$ an improper integral? For both I need to evaluate the integral or show that it's divergent. I have no idea what to do and need serious help for math homework since we never covered this in our Calc 1 class.
2014/08/12
[ "https://math.stackexchange.com/questions/894646", "https://math.stackexchange.com", "https://math.stackexchange.com/users/169232/" ]
Improper integrals occur in primarily two ways: an bound that goes off to infinity or a bound where the function goes off to infinity (infinitely wide vs. infinitely tall). Clearly anything of the form$$\int\_0^\infty f(x)\mathrm{d}x$$ is improper and we have to really consider what happens as we *approach* infinity. Which should scream **limit**! So we set it up as follows: $$\lim\_{b\to\infty}\int\_0^b f(x)\mathrm{d}x$$ and perform the integration as normal, and *then* take the limit. The other possibility is when the function in the integral does funky things on our bounds (such as going off to infinity or dividing by zero, etc.) One example is this simple integral: $$\int\_0^1 \frac{\mathrm{d}x}{x-1}$$ This could potentially have an infinity area (look at the [graph](http://www.wolframalpha.com/input/?i=1%2F%281-x%29%20from%200%20to%201)) because as we get close to $x=1$ we are getting close to dividing by $0$. So we pull the same trick and we look at the integral $$\int\_0^{0.9} \frac{\mathrm{d}x}{x-1}$$ and then $$\int\_0^{0.99} \frac{\mathrm{d}x}{x-1}$$ and it doesn't take long to realize you're taking a limit. $$\lim\_{b\to1}\int\_0^b \frac{\mathrm{d}x}{x-1}$$ where this time $b$ approaches a finite value. --- Now, to visit your examples: neither of them have an infinite bound and so our first type of improper integral can be ruled out. Now we see if we divide by $0$ or take the $\log$ of $0$ or other math no-no's. (As Andre corrected me) The first one has the $\ln{1}=0$ in a denominator which is the same as trying to divide by $0$ and therefore, we have an improper integral. And we would want to solve: $$\lim\_{b\to 1^+}\int\_b^e \frac{\mathrm{d}x}{x\left(\ln{x}\right)^{1/2}}$$ and solve the integral first (in terms of a new variable $b$) and *then* take the limit, as if it had nothing to do with an integral. In the current state, it seems that the second integral has no such "funk" and therefore is not improper. I hope this helps clear up what an improper integral is! --- EDIT: I do want to point out that if the bounds on the second integral were this: $$\int\_{-2}^0\frac{\mathrm{d}x}{x^2+6x+8}$$ then we *would* have an improper integral because if we look at $x=-2$ we end up with $1/0$ and that's a no-no. So we, instead, consider: $$\lim\_{b\to -2^+}\int\_b^0\frac{\mathrm{d}x}{x^2+6x+8}$$ and solve the integral first (in terms of a new variable $b$) and *then* take the limit, as if it had nothing to do with an integral.
12,208,336
Is it possible to apply a fade out effect on the jQuery UI modal dialog box overlay? The issue is that the overlay div is destroyed when the modal dialog box is closed preventing any kind of animation. This is the code I have that would work if the overlay div was not destroyed on close. ``` $("#edit-dialog-box").dialog( { autoOpen: false, modal: true, width: "30em", show: "fade", hide: "fade", open: function() { $(".ui-widget-overlay").hide().fadeIn(); }, close: function() { $(".ui-widget-overlay").fadeOut(); } }); ```
2012/08/31
[ "https://Stackoverflow.com/questions/12208336", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1078268/" ]
Demo: <http://jsfiddle.net/276Ft/2/> ``` $('#dialog').dialog({ autoOpen: true, modal: true, width: '100px', height: '100px', show: 'fade', hide: 'fade', open: function () { $('.ui-widget-overlay', this).hide().fadeIn(); $('.ui-icon-closethick').bind('click.close', function () { $('.ui-widget-overlay').fadeOut(function () { $('.ui-icon-closethick').unbind('click.close'); $('.ui-icon-closethick').trigger('click'); }); return false; }); } }); ``` ​
38,874,837
I have a query that looks like the following: ``` SELECT time_start, some_count FROM foo WHERE user_id = 1 AND DATE(time_start) = '2016-07-27' ORDER BY some_count DESC, time_start DESC LIMIT 1; ``` What this does is return me one row, where some\_count is the highest count for `user_id = 1`. It also gives me the time stamp which is the most current for that `some_count`, as `some_count` could be the same for multiple `time_start` values and I want the most current one. Now I'm trying to do is run a query that will figure this out for every single `user_id` that occurred at least once for a specific date, in this case `2016-07-27`. Ultimately it's going to probably require a GROUP BY as I'm looking for a group maximum per `user_id` What's the best way to write a query of that nature?
2016/08/10
[ "https://Stackoverflow.com/questions/38874837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/175836/" ]
I am sharing two of my approaches. **Approach #1 (scalable):** Using `MySQL user_defined variables` ``` SELECT t.user_id, t.time_start, t.time_stop, t.some_count FROM ( SELECT user_id, time_start, time_stop, some_count, IF(@sameUser = user_id, @rn := @rn + 1, IF(@sameUser := user_id, @rn := 1, @rn := 1) ) AS row_number FROM foo CROSS JOIN ( SELECT @sameUser := - 1, @rn := 1 ) var WHERE DATE(time_start) = '2016-07-27' ORDER BY user_id, some_count DESC, time_stop DESC ) AS t WHERE t.row_number <= 1 ORDER BY t.user_id; ``` Scalable because if you want latest n rows for each user then you just need to change this line : `... WHERE t.row_number <= n...` I can add explanation later if the query provides expected result --- **Approach #2:(Not scalable)** Using `INNER JOIN and GROUP BY` ``` SELECT F.user_id, F.some_count, F.time_start, MAX(F.time_stop) AS max_time_stop FROM foo F INNER JOIN ( SELECT user_id, MAX(some_count) AS max_some_count FROM foo WHERE DATE(time_start) = '2016-07-27' GROUP BY user_id ) AS t ON F.user_id = t.user_id AND F.some_count = t.max_some_count WHERE DATE(time_start) = '2016-07-27' GROUP BY F.user_id ```
14,355,712
> > **Possible Duplicate:** > > [How to add a JComboBox to a JTable cell?](https://stackoverflow.com/questions/2059229/how-to-add-a-jcombobox-to-a-jtable-cell) > > > I'm finding it difficult to add `JComboBox` to one of the cells of a `JTable`, I tried the code below but it's not working.. **How can I add jcombobox to a particular cell?** On pressing `enter` a new `jcombobox` should be added automatically to the desired column. ``` jTable1 = new javax.swing.JTable(); mod=new DefaultTableModel(); mod.addColumn("No"); mod.addColumn("Item ID"); mod.addColumn("Units"); mod.addColumn("Amount"); mod.addColumn("UOM"); mod.addColumn("Delivery Date"); mod.addColumn("Total Amount"); mod.addColumn("Notes"); mod.addColumn("Received"); mod.addRow(new Object [][] { {1, null, null, null, null, null, null, null, null} }); jTable1.setModel(mod); jTable1.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(generateBox())); jTable1.setColumnSelectionAllowed(true); Code to generate ComboBox private JComboBox generateBox() { JComboBox bx=null; Connection con=CPool.getConnection(); try { Statement st=con.createStatement(); String query="select distinct inid from inventory where company_code="+"'"+ims.MainWindow.cc+"'"; ResultSet rs=st.executeQuery(query); bx=new JComboBox(); while(rs.next()){ bx.addItem(rs.getString(1)); } CPool.closeConnection(con); CPool.closeStatement(st); CPool.closeResultSet(rs); }catch(Exception x) { System.out.println(x.getMessage()); } return bx; } ```
2013/01/16
[ "https://Stackoverflow.com/questions/14355712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1955017/" ]
Look at this link it will help you <http://docs.oracle.com/javase/tutorial/uiswing/components/table.html> ![enter image description here](https://i.stack.imgur.com/0CG6G.png) and the code : <http://docs.oracle.com/javase/tutorial/uiswing/examples/components/TableRenderDemoProject/src/components/TableRenderDemo.java>
26,994,020
Here is the Reddit widget code: I'd like for every clickable link in the reddit widget box to open up into a new tab. Any idea of how to do this? Thanks For all your help!
2014/11/18
[ "https://Stackoverflow.com/questions/26994020", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4265442/" ]
So, for example, reddit generates this for you for a widget code. The problem is that it will open any links in the same window. `<script src="http://www.reddit.com/r/satire/hot/.embed?limit=5&t=all" type="text/javascript"></script>` You can make it open in a new tab/window (based on browser settings) by adding **&target=blank** : `<script src="http://www.reddit.com/r/satire/hot/.embed?limit=5&t=all&style=off&target=blank" type="text/javascript"></script>` Adding the bolded script seems to do the trick just fine.
24,367,854
I am writing a simple form at work using HTML and have added JavaScript to the page to allow users to add extra rows to a table. This table has input type="Text" tags and select tags. When the user clicks the button to add a row, the JavaScript adds a row, but clears the input and select tags. My script is ``` var x = x + 1; function another() { x = x + 1; y = y + 1; var bigTable = document.getElementById("bigTable"); bigTable.innerHTML += ("<TR><TD CLASS=\"bigTable2\" ALIGN=\"Center\"><SELECT NAME=\"PO" + x + "\"><OPTION>Select</OPTION><OPTION>1234567890</OPTION></SELECT> </TD><TD CLASS=\"bigTable2\" ALIGN=\"Center\"><INPUT TYPE=\"Text\" NAME=\"SKU" + x + "\"></TD><TD CLASS=\"bigTable2\" ALIGN=\"Center\"><INPUT TYPE=\"Text\" NAME=\"modelNum" + x + "\"></TD><TD CLASS=\"bigTable2\" ALIGN=\"Center\"><INPUT TYPE=\"Text\" NAME=\"itemNum" + x + "\"></TD><TD CLASS=\"bigTable2\" ALIGN=\"Center\"><INPUT TYPE=\"Text\" NAME=\"qty" + x + "\" ID=\"qty"+x+"\" onBlur=\"total();\"></TD></TR>"); } ``` I'm not sure what the issue is here. Is the "+=" statement basically resetting my table like an = statement would? EDIT: I don't know how to get all of the code to appear, but what is displayed is not all of my code. I have a basic Table and using JavaScript use a += statement to add HTML to it. EDIT: My table is this: ``` <TABLE ID="bigTable"> <TR> <TH>P.O. #</TH> <TH>SKU #</TH> <TH>Model #</TH> <TH>Item #</TH> <TH>Quantity</TH> </TR> <TR> <TD CLASS="bigTable" ALIGN="Center"> <SELECT NAME="PO1"> <OPTION>Select</OPTION> <OPTION>1234567890</OPTION> </SELECT> </TD> <TD CLASS="bigTable2" ALIGN="Center"><INPUT TYPE="Text" NAME="SKU1"></TD> <TD CLASS="bigTable2" ALIGN="Center"><INPUT TYPE="Text" NAME="modelNum1"></TD> <TD CLASS="bigTable2" ALIGN="Center"><INPUT TYPE="Text" NAME="itemNum1"></TD> <TD CLASS="bigTable2" ALIGN="Center"><INPUT TYPE="Text" NAME="qty1" ID="qty1" onBlur="total();"></TD> </TR> </TABLE> ``` My JavaScript Replicates everything between the tags. And I use the variable x to update the number in the names for the inputs and dropdowns. Variable Y is used to increment a calculation function.
2014/06/23
[ "https://Stackoverflow.com/questions/24367854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3767679/" ]
When you edit the `innerHTML` of a HTML element, the entire DOM gets re-parsed. Since the input's values aren't actually stored in the input elements's HTML, they are cleared. An option would be to use DOM manipulation to add the row: ``` function another(){ x = x + 1; y = y + 1; var bigTable = document.getElementById("bigTable"); vat tr = document.createElement('tr'); tr.innerHTML = ("<td class='bigTable2' align='Center'><select name='PO" + x + "'><option>select</option><option>1234567890</option></select></td>"+ "<td class='bigTable2' align='Center'><input type='Text' name='SKU" + x + "'></td>"+ "<td class='bigTable2' align='Center'><input type='Text' name='modelNum" + x + "'></td>"+ "<td class='bigTable2' align='Center'><input type='Text' name='itemNum" + x + "'></td>"+ "<td class='bigTable2' align='Center'><input type='Text' name='qty" + x + "' ID='qty" + x + "' onBlur='total();'></td>"); bigTable.appendChild(tr); } ``` Notice how the string no longer contains a `<tr>` tag. This codes creates a `tr` element, then adds the rows to it, then adds that whole, (parsed), `tr` to the table. (I also changed the tags / attributes to lowercase and replaced all `\"` with `'` to make it more readable)
61,226
I have MacBook Pro: ``` 13-inch, Late 2011 2.4 GHz Intel Core i5 4 GB 1333 MHz DDR3 Intel HD Graphics 3000 384MB OS X Lion 10.7.4 ``` When it plays a video, the CPU temperature goes over 90 degrees celsius and the fan makes loud noises. Is this normal? Or should I change speed of fan and make it faster for better cooling?
2012/08/19
[ "https://apple.stackexchange.com/questions/61226", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/27671/" ]
I believe that it is common for the CPU to reach 90°C under heavy load. However a simple video should not bump an i5 into that region. Depending on the footage and format you are playing back you might want to try a different player (vlc mplayerX). If you are playing back flash HD videos in your browser (especially multiple streams simultaneously), that behavior might be common (due to the bad flash performance on os x). So much for the software. Secondly you should take care of the outer temperature (e.g.is your computer in a very hot room) and even more importantly where your notebook is placed. e.g. does it sit on a carpet or any other good insulating soft cushiony surface that prevents heat from leaving your computer. Thirdly you might want to take a look in the activity monitor and see whats using your cpu. (Maybe some background application e.g. spotlight indexing new pdfs)
34,535,602
I've been using Highcharts on a Wordpress website for about 9 months without problems. Last week I updated to Wordpress 4.4 and soon after I noticed that my charts didn't render properly anymore (may be unrelated, not sure). In Chrome or Safari the div doesn't expand height-wise at all so the charts aren't legible. In Firefox, they initially displayed the same behavior as the other two browsers, but now just an empty div displays. I tried changing the order I list my scripts in my header.php file, but that didn't seem to have any effect. I also removed all other scripts except the highcharts script, but that didn't work either. I've also tried adjusting code in my function.php file using this method on CSS Tricks: <https://css-tricks.com/snippets/wordpress/include-jquery-in-wordpress-theme/> but no luck there either. Here's an example of a chart that's not rendering correctly: <http://siliconvalleyindicators.org/data/people/talent-flows-diversity/total-science-engineering-degrees-conferred/> Any advice is much appreciated.
2015/12/30
[ "https://Stackoverflow.com/questions/34535602", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5731796/" ]
You have this element for holding chart: ``` <div style="width:100%; height:100%;" data-highcharts-chart="0" id="hc1"> ``` Replace heigh with some value with px, em etc. ``` style="width:100%; height:200px;" ``` This should fix your problem.
3,540,234
There is a well-known theorem in mathematical analysis that says > > Suppose $f:M\to N$ is a function from a metric space $(M,d\_M)$ to another metric space $(N,d\_N)$. Assume that $M$ is compact. Then $f$ is uniformly continuous over $(M,d\_M)$. > > > For now, let us take $M=[a,b]$, $N=\mathbb{R}$, $d\_M=d\_N=|\cdot|$. I have seen two different proofs for this case. * T. A. Apostol, Calculus, Volume 1, 2nd Edition, Page 152, 1967. * C. C. Pugh, Real Mathematical Analysis, 2nd Edition, Page 85, 2015. Apostol argues by contradiction using the method of bisections and the least upper bound property. Pugh also explains by contradiction but prefers to use a technique that one of my teachers called it continuous induction to prove that $[a\,\,\,b]$ is sequentially compact and then uses this property to prove the theorem. Both proofs can be found on the pages mentioned above. Recently, I noticed that Pugh has suggested another approach in exercise 43 of chapter 1 on page 52. However, I couldn't riddle it out. Here is the question > > 43. Prove that a continuous function defined on an interval $[a\,\,\,b]$ is uniformaly continuous. > > > **Hint**. Let $\epsilon>0$ be given. Think of $\epsilon$ as fixed and consider the sets > \begin{align\*}A(\delta)&=\{u\in[a,b]\,|\,\text{if}\,x,t\in[a,u]\,\text{and}\,|x-t|<\delta\,\text{then}\,|f(x)-f(t)|<\epsilon\}, \\ > A&=\bigcup\_{\delta>0}A(\delta). > \end{align\*} > Using the least upper bound property, prove that $b\in A$. Infer that $f$ is uniformly continuous. > > > Can you shed some light on what Pugh is trying to suggest in the hint? --- **Uniform Continuity** In the definition of continuity we have that $$\forall x\in[a,b],\,\,\forall\epsilon>0,\,\,\exists\delta>0,\,\,\forall t\in[a,b]\,\wedge\,|t-x|<\delta\,\implies|f(t)-f(x)|<\epsilon$$ Here the delta depends on $x$ and $\epsilon$. Now, fix $\epsilon$ and let $\Delta\_{\epsilon}$ be the set that contains all values of $\delta$ corresponding to different $x$'s. Then uniform continuity is just telling us that $\Delta\_\epsilon$ has a minimum. Consequently, this means that there is a $\delta$ that works for all $x\in[a,b]$. This leads to the following definition $$\forall\epsilon>0,\,\,\exists\delta>0,\,\,\forall x\in[a,b],\,\,\forall t\in[a,b]\,\wedge\,|t-x|<\delta\,\implies|f(t)-f(x)|<\epsilon$$ where $\delta$ only depends on $\epsilon$.
2020/02/09
[ "https://math.stackexchange.com/questions/3540234", "https://math.stackexchange.com", "https://math.stackexchange.com/users/267844/" ]
Note that $a\in A$, since $x,t\in[a,a]$ implies $|f(x)-f(t)|=0<\epsilon$. Assume $c\in A$. Then, from continuity at $c$ there is $\delta$ such that if $|x-c|<\delta$ then $|f(x)-f(c)|<\epsilon/2$. Then, if $x,t$ are $\delta$-close to $c$, then $|f(x)-f(t)|\leq|f(x)-f(c)|+|f(t)-f(c)|<\epsilon$. Therefore, $[c,\delta/2]\subset A$. Let $b'$ be the supremum of the $c$ such that $[a,c]\subset A$. The argument above shows that if $b'<b$, then there is $\delta>0$ such that $[b',b+\delta]\subset A$ contradicting that $b'$ is the supremum. Therefore, $b'=b$. --- The argument has an inductive structure in that you check it for the initial point $a$. Then, assuming the conclusion for a set $[a,b']$ you prove that it is satisfied for $[a,b'+\delta]$ for some $\delta>0$. The combination of them gives that it holds on $[a,b]$ all $b$.
111,765
uC: PIC18F46K20 I want to scan, in a loop, different ports and test different pins on each port. I have different target boards so I want to be able to quickly configure each board in CONST arrays. So I created arrays like these: ``` const char my_ports[4] = {PORTB, PORTB, PORTD, PORTA}; // <- this is the PROBLEM causing line const char my_pins[4] = {3, 7, 1, 4}; ``` in order to be able to scan those ports in a loop: ``` // NEW version of the func. void pin_update(void) { for (k=0; k<=3; k++) { if (my_ports[k] & my_pins[k]) { // and actions here ........ } } } ``` --- But compiler comes up with an error : ``` "my_ports[] ... constant expression required" ``` I used the approach of passing the port name (eg. PORTB) in previous version of the code when each pin was tested individually, eg. : ``` pin_update(PORTB, 3); // ... pin_update(PORTD, 1); // OLD version of the func: void pin_update(char prt, char pn) { if (prt & pn) { // and actions here ........ } } ``` and all was OK and code worked properly. But as you see PORTB is hard coded in a parameter list. And now I want to run the above 'pin updates' in a loop. So problem came out when I wanted to list port names in CONST array. I tried various things with casting to ports' addresses etc - nothing worked. Compiler still did not like it.
2014/05/25
[ "https://electronics.stackexchange.com/questions/111765", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/41276/" ]
You're doing this the hard way. First off, R3 is not your problem. 12 volts / 240k is 50 uA. If you look at the data sheet for an LM386 <http://www.ti.com/lit/ds/symlink/lm386.pdf> p.4 "Quiescent Current", you'll see that for a 12 volt supply the LM386 will draw about 5 mA, or 100 times more than R3. This is with no load on the output. So the question you need to ask is "How much current can I afford to supply in the off condition?". If the answer is 1 uA, then the following circuit will do you fine. Just be careful about picking Q1 - the attribute you're looking for is Idss with Vg = 0. This varies with model, but I've seen it at 1 uA. If 1 uA is too much, then I suggest using your float switch to activate a small relay, and use the contacts of this relay to drive a more powerful relay which will actually drive the pump. ![schematic](https://i.stack.imgur.com/6wLRk.png) [simulate this circuit](/plugins/schematics?image=http%3a%2f%2fi.stack.imgur.com%2f6wLRk.png) – Schematic created using [CircuitLab](https://www.circuitlab.com/)
65,299,556
[**test spreadsheet**](https://docs.google.com/spreadsheets/d/1Ay9HVFTOlAiZ6P-nkjzoH-Erh48_zlX2ZFsU2VG22Fk/edit?usp=sharing) Tab `'Raw Data'` contains a combination of "attendance sheets" from multiple activities. Students are in multiple activities on the same Date. Tab `'Result'` lists all unique Students and Dates. **Goal:** `'Result'!B3:D11` marks P or A if that student was P for ***any*** of the activities on that Date. *For example:* On 12/5, Evan was marked A, A, and P in his activities - so he should be marked P for that Date. If these were numbers, I think I'd be able to use SMALL or LARGE in combination with INDEX/MATCH to count the results...but I'm unsure how to make this formula work with A's and P's.
2020/12/15
[ "https://Stackoverflow.com/questions/65299556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14337312/" ]
Since in your sample sheet you do not use a formula for Unique students I suggest -in cell `F3`- you use **``` =UNIQUE(FILTER($A$2:$A$33,B2:B33<>"")) ```** We can now use the above formula as part of the following one in cell `G2` so as to get the desired result ``` =ArrayFormula({B1;IF(COUNTIFS($A$2:$A,"="&UNIQUE(FILTER($A$2:$A,B2:B<>"")),B2:B,"=P")>0,"P","A")}) ``` Drag the above to adjacent cells to the right, to get the rest of the columns. *(Please adjust ranges to your needs)* [![enter image description here](https://i.stack.imgur.com/0LFSO.png)](https://i.stack.imgur.com/0LFSO.png) Functions used: * [`ArrayFormula`](https://support.google.com/docs/answer/3093275) * [`IF`](https://support.google.com/docs/answer/3093364) * [`COUNTIFS`](https://support.google.com/docs/answer/3256550) * [`UNIQUE`](https://support.google.com/docs/answer/3093198) * [`FILTER`](https://support.google.com/docs/answer/3093197)
4,391,219
Our app has a tab control that shows a variable number of tabs. Most of the time, there are a handful of tabs, and the "tabbed" metaphor is simple and easy to use. But on rare occasions (when working with certain types of data), we might need many more tabs than will fit across the screen. When that happens, the trusty tab control is no longer a good user experience. Whether you do multiple rows of tabs, or the little scroll buttons, finding the tab you want becomes a huge headache. Visual Studio's editor can handle this situation with relative grace. It only shows a limited number of tabs at a time (however many will fit across the screen); and if you want something that's not currently visible, there's a dropdown button that shows the complete list. **Are there any third-party WinForms tab controls that offer similar functionality -- a few tabs at a time, plus a dropdown?** There will actually be times when even the dropdown list would be too long to fit on the screen, so it would be helpful to know how any tab controls deal with that. A scrollbar (where you can drag the thumb quickly to the right neighborhood) would be great; so would incremental searching using the keyboard. For purposes of this question, assume that replacing the tabs with some other UI metaphor (e.g. a listbox down the left side) is not an option. (We are exploring that, but that's not what this question is about.)
2010/12/08
[ "https://Stackoverflow.com/questions/4391219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/87399/" ]
Telerik have a commercial [Winforms control library](http://www.telerik.com/products/winforms.aspx) which has a control called [RadPageView](http://www.telerik.com/products/winforms/pageview.aspx). This can behave similar to what you describe when in StripView mode. The library is costly just for this one control though. DevExpress also have one as part of their XtraEditors library called [XtraTabControl](http://www.devexpress.com/Products/NET/Controls/WinForms/Editors/editors/XtraTabControl.xml). This has an "Additional paint style emulating the Visual Studio 2005 tabbed interface", although there are no screen shots of what that looks like. There is a screen shot on [this](http://documentation.devexpress.com/#WindowsForms/clsDevExpressXtraTabXtraTabControltopic) page, although it doesn't look like what you require.
19,291,499
How can I change the output directory in Google glog? I only found `google::SetLogDestination(google::LogSeverity, const char* path)` tried it with: ``` google::SetLogDestination(ERROR, "C:\\log\\error.log); google::InitGoogleLogging("Test"); LOG(ERROR) << "TEST"; ``` but nothing was written! Btw.: if you suggest another lightweight, easy to use and thread safe library please let me know! Thx for any help!
2013/10/10
[ "https://Stackoverflow.com/questions/19291499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/384556/" ]
You can also do one of the following: Pass the log directory as a commandline argument as long as you have the GFlgas library installed: ``` ./your_application --log_dir=/some/log/directory ``` If you don't want to pass it in the commandline and instead set it in the source: ``` FLAGS_log_dir = "/some/log/directory"; ``` If the Google gflags library isn't installed you can set it as an environment variable: ``` GLOG_log_dir=/some/log/directory ./your_application ```
2,156,569
I have the following code to return the length of a cycle in a string: ``` module Main where import Data.List detec ys n | 2*n > (length ys) = error "no cycle" | t == h = (2*n - n) | otherwise = detec ys (n+1) where t = ys !! n h = if n == 0 then ys !! 1 else ys !! (n*2) f x = detec (show x) 0 answer = map f [1/x|x<-[1..100]] ``` But what I don't know how to do is make it ignore the `"no cycle"` exception so that the list produced only contains the lengths of the strings which are cyclic. How can I do this?
2010/01/28
[ "https://Stackoverflow.com/questions/2156569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/150851/" ]
Please don't use `error` to implement logic where the "erroneous" result is expected to occur. Instead, why not return `Maybe n` instead of just `n`, then [use `catMaybes`](http://haskell.org/ghc/docs/latest/html/libraries/base-4.2.0.0/Data-Maybe.html#v%3AcatMaybes) to filter out the `Nothing`s? The changes are easy enough: ``` module Main where import Data.List import Data.Maybe detec ys n | 2*n > (length ys) = Nothing | t == h = Just (2*n - n) | otherwise = detec ys (n+1) where t = ys !! n h = if n == 0 then ys !! 1 else ys !! (n*2) f x = detec (show x) 0 answer = catMaybes $ map f [1/x|x<-[1..100]] ``` By the way, you're indexing past the end of the list; perhaps you meant to check `2*n + 1 > length ys`? Drifting slightly off topic, I'd like to mention that `!!` and `length` are, for the most part, both inefficient and non-idiomatic when applied to lists, especially in an iterating construct like this. The list type is basically a *cons cell list*, which is an intrinsically recursive data structure, and is emphatically *not* an array. Ideally you should avoid doing anything with a list that can't be easily expressed with pattern matching, e.g., `f (x:xs) = ...`.
5,959
*Ce* and *ça* both mean the same thing (this) in French, so what is the difference between them? When would someone use one over the other?
2013/03/11
[ "https://french.stackexchange.com/questions/5959", "https://french.stackexchange.com", "https://french.stackexchange.com/users/1114/" ]
This answer will be about the pronouns, but note that *ce* (with variants *cet*, *cette*) is also a demonstrative adjective and as such will be followed by a noun and that *ça* should not be confused with *çà* which is an old synonym of *ici*. *Ça* is an alternative form of *cela*; they can replace each other in most if not all contexts, but *ça* tend to be used more often (but not exclusively) when speaking, while *cela* tend to be used more often (but not exclusively) in writing. One case where *cela* is used more often both orally and in writing is when it is opposed with *ceci*. *Ce*, *ceci*, *cela* and *ça* are the neutral demonstrative pronouns. They don't replace a noun (forms with *celui*, *celle*, *ceux*, *celles* are used in those cases) but something implied or (part of) a sentence. When they are opposed, *ceci* is used for the nearer (in space, in time or in the discourse), *cela* (or sometimes *ça*) for the further. Alone, *ceci* is for something quite near and *cela* or *ça* for something quite far, but *cela* is also used for things near, especially for part of sentences which precedes the pronoun. Usages of *ce* are more limited: * in *ce que*, *ce qui*, *ce dont*, ... then it stands for a thing (it used to be able to stand for a person, but that's rare nowadays) or a (part of) a sentence. * as subject of *être*, *ce* stands for what comes before (in that case it can be redundant and only used for emphasis), or the situation. * it is also sometimes used as the subject of *pouvoir* or *devoir*, when used as modal verbs (aka semi-auxiliaries). * there are some other usages, more or less literary (*ce me semble*), more or less fixed remnants of older structures (*Ce disant, ...*) and it is sometimes replaced with *ça* for emphasis.
24,411,934
I have a small server and small client. The code has been extrapolated to focus on the problem at hand. I have a client that sends a POST request to the server. The server responds with a json object. I am unable to see the json response object from within the node.js client. However, if I make a curl request, I can see it... //SERVER ``` var restify = require('restify'), Logger = require('bunyan'), api = require('./routes/api'), util = require('util'), fs = require('fs'); //START SERVER var server = restify.createServer({ name: 'image-server', log: log }) server.listen(7000, function () { console.log('%s listening at %s', server.name, server.url) }) server.use(restify.fullResponse()); server.use(restify.bodyParser()); //change from github var user = {username: "usr", password: "pwd"}; //auth middleware server.use(function(req,res,next){ if(req.params.username==user.username && req.params.password == user.password){ return next(); }else{ res.send(401); } }); server.post('/doc/', function(req,res){ var objToJson = {"result" : "success", "user" : "simon", "location" : "someloc"}; console.log("saved new doc. res: " + util.inspect(objToJson)); res.send(objToJson); }); ``` //CLIENT ``` var formdata = require('form-data'); var request = require('request'); var util = require('util'); var fs = require('fs'); var form = new formdata(); form.append('username', 'usr'); form.append('password', 'pwd'); form.append('user', 'someemail@gmail.com'); form.append('file', fs.createReadStream('/some/file.png')); form.append('filename', "roger123131.png"); form.submit('http://0.0.0.0:7000/doc', function(err, res) { console.log(res.statusCode); console.log(res.body); console.log( "here." + util.inspect(res)); process.exit(); }); ``` In the client, I use form-data module. I need to send over the file, though I'm not sure if this is related/pertinent to the problem at hand. //CURL REQUEST ``` curl -v --form username=usr --form password=pwd --form file=@/tmp/0000b.jpg --form user=someemail http://0.0.0.0:7000/doc ``` The output of the curl request works. My question is, why can i not see the json response when I dump the response object in my node.js client code, but I can when making a request using curl? I'm sure the answer is simple... EDIT: Here is the output of the node.js client, showing the response object with no evidence of the json object/string: ``` 200 undefined here.{ _readableState: { highWaterMark: 16384, buffer: [], length: 0, pipes: null, pipesCount: 0, flowing: false, ended: false, endEmitted: false, reading: true, calledRead: true, sync: false, needReadable: true, emittedReadable: false, readableListening: false, objectMode: false, defaultEncoding: 'utf8', ranOut: false, awaitDrain: 0, readingMore: false, decoder: null, encoding: null }, readable: true, domain: null, _events: { end: [Function: responseOnEnd], readable: [Function] }, _maxListeners: 10, socket: { _connecting: false, _handle: { fd: 10, writeQueueSize: 0, owner: [Circular], onread: [Function: onread], reading: true }, _readableState: { highWaterMark: 16384, buffer: [], length: 0, pipes: null, pipesCount: 0, flowing: false, ended: false, endEmitted: false, reading: true, calledRead: true, sync: false, needReadable: true, emittedReadable: false, readableListening: false, objectMode: false, defaultEncoding: 'utf8', ranOut: false, awaitDrain: 0, readingMore: false, decoder: null, encoding: null }, readable: true, domain: null, _events: { end: [Object], finish: [Function: onSocketFinish], _socketEnd: [Function: onSocketEnd], free: [Function], close: [Object], agentRemove: [Function], drain: [Function: ondrain], error: [Function: socketErrorListener] }, _maxListeners: 10, _writableState: { highWaterMark: 16384, objectMode: false, needDrain: false, ending: false, ended: false, finished: false, decodeStrings: false, defaultEncoding: 'utf8', length: 0, writing: false, sync: false, bufferProcessing: false, onwrite: [Function], writecb: null, writelen: 0, buffer: [], errorEmitted: false }, writable: true, allowHalfOpen: false, onend: [Function: socketOnEnd], destroyed: false, bytesRead: 587, _bytesDispatched: 23536, _pendingData: null, _pendingEncoding: '', parser: { _headers: [], _url: '', onHeaders: [Function: parserOnHeaders], onHeadersComplete: [Function: parserOnHeadersComplete], onBody: [Function: parserOnBody], onMessageComplete: [Function: parserOnMessageComplete], socket: [Circular], incoming: [Circular], maxHeaderPairs: 2000, onIncoming: [Function: parserOnIncomingClient] }, _httpMessage: { domain: null, _events: [Object], _maxListeners: 10, output: [], outputEncodings: [], writable: true, _last: false, chunkedEncoding: false, shouldKeepAlive: true, useChunkedEncodingByDefault: true, sendDate: false, _headerSent: true, _header: 'POST /doc HTTP/1.1\r\ncontent-type: multipart/form-data; boundary=--------------------------994987473640480876924123\r\nHost: 0.0.0.0:7000\r\nContent-Length: 23351\r\nConnection: keep-alive\r\n\r\n', _hasBody: true, _trailer: '', finished: true, _hangupClose: false, socket: [Circular], connection: [Circular], agent: [Object], socketPath: undefined, method: 'POST', path: '/doc', _headers: [Object], _headerNames: [Object], parser: [Object], res: [Circular] }, ondata: [Function: socketOnData] }, connection: { _connecting: false, _handle: { fd: 10, writeQueueSize: 0, owner: [Circular], onread: [Function: onread], reading: true }, _readableState: { highWaterMark: 16384, buffer: [], length: 0, pipes: null, pipesCount: 0, flowing: false, ended: false, endEmitted: false, reading: true, calledRead: true, sync: false, needReadable: true, emittedReadable: false, readableListening: false, objectMode: false, defaultEncoding: 'utf8', ranOut: false, awaitDrain: 0, readingMore: false, decoder: null, encoding: null }, readable: true, domain: null, _events: { end: [Object], finish: [Function: onSocketFinish], _socketEnd: [Function: onSocketEnd], free: [Function], close: [Object], agentRemove: [Function], drain: [Function: ondrain], error: [Function: socketErrorListener] }, _maxListeners: 10, _writableState: { highWaterMark: 16384, objectMode: false, needDrain: false, ending: false, ended: false, finished: false, decodeStrings: false, defaultEncoding: 'utf8', length: 0, writing: false, sync: false, bufferProcessing: false, onwrite: [Function], writecb: null, writelen: 0, buffer: [], errorEmitted: false }, writable: true, allowHalfOpen: false, onend: [Function: socketOnEnd], destroyed: false, bytesRead: 587, _bytesDispatched: 23536, _pendingData: null, _pendingEncoding: '', parser: { _headers: [], _url: '', onHeaders: [Function: parserOnHeaders], onHeadersComplete: [Function: parserOnHeadersComplete], onBody: [Function: parserOnBody], onMessageComplete: [Function: parserOnMessageComplete], socket: [Circular], incoming: [Circular], maxHeaderPairs: 2000, onIncoming: [Function: parserOnIncomingClient] }, _httpMessage: { domain: null, _events: [Object], _maxListeners: 10, output: [], outputEncodings: [], writable: true, _last: false, chunkedEncoding: false, shouldKeepAlive: true, useChunkedEncodingByDefault: true, sendDate: false, _headerSent: true, _header: 'POST /doc HTTP/1.1\r\ncontent-type: multipart/form-data; boundary=--------------------------994987473640480876924123\r\nHost: 0.0.0.0:7000\r\nContent-Length: 23351\r\nConnection: keep-alive\r\n\r\n', _hasBody: true, _trailer: '', finished: true, _hangupClose: false, socket: [Circular], connection: [Circular], agent: [Object], socketPath: undefined, method: 'POST', path: '/doc', _headers: [Object], _headerNames: [Object], parser: [Object], res: [Circular] }, ondata: [Function: socketOnData] }, httpVersion: '1.1', complete: false, headers: { 'content-type': 'application/json', 'content-length': '56', 'access-control-allow-origin': '*', 'access-control-allow-headers': 'Accept, Accept-Version, Content-Length, Content-MD5, Content-Type, Date, Api-Version, Response-Time', 'access-control-allow-methods': 'POST', 'access-control-expose-headers': 'Api-Version, Request-Id, Response-Time', connection: 'Keep-Alive', 'content-md5': '/HLlB0jKu9S+l17eGyJfxg==', date: 'Wed, 25 Jun 2014 15:40:00 GMT', server: 'image-server', 'request-id': 'f7ca8390-fc7e-11e3-aa4e-e9c4573d9f1d', 'response-time': '4' }, trailers: {}, _pendings: [], _pendingIndex: 0, url: '', method: null, statusCode: 200, client: { _connecting: false, _handle: { fd: 10, writeQueueSize: 0, owner: [Circular], onread: [Function: onread], reading: true }, _readableState: { highWaterMark: 16384, buffer: [], length: 0, pipes: null, pipesCount: 0, flowing: false, ended: false, endEmitted: false, reading: true, calledRead: true, sync: false, needReadable: true, emittedReadable: false, readableListening: false, objectMode: false, defaultEncoding: 'utf8', ranOut: false, awaitDrain: 0, readingMore: false, decoder: null, encoding: null }, readable: true, domain: null, _events: { end: [Object], finish: [Function: onSocketFinish], _socketEnd: [Function: onSocketEnd], free: [Function], close: [Object], agentRemove: [Function], drain: [Function: ondrain], error: [Function: socketErrorListener] }, _maxListeners: 10, _writableState: { highWaterMark: 16384, objectMode: false, needDrain: false, ending: false, ended: false, finished: false, decodeStrings: false, defaultEncoding: 'utf8', length: 0, writing: false, sync: false, bufferProcessing: false, onwrite: [Function], writecb: null, writelen: 0, buffer: [], errorEmitted: false }, writable: true, allowHalfOpen: false, onend: [Function: socketOnEnd], destroyed: false, bytesRead: 587, _bytesDispatched: 23536, _pendingData: null, _pendingEncoding: '', parser: { _headers: [], _url: '', onHeaders: [Function: parserOnHeaders], onHeadersComplete: [Function: parserOnHeadersComplete], onBody: [Function: parserOnBody], onMessageComplete: [Function: parserOnMessageComplete], socket: [Circular], incoming: [Circular], maxHeaderPairs: 2000, onIncoming: [Function: parserOnIncomingClient] }, _httpMessage: { domain: null, _events: [Object], _maxListeners: 10, output: [], outputEncodings: [], writable: true, _last: false, chunkedEncoding: false, shouldKeepAlive: true, useChunkedEncodingByDefault: true, sendDate: false, _headerSent: true, _header: 'POST /doc HTTP/1.1\r\ncontent-type: multipart/form-data; boundary=--------------------------994987473640480876924123\r\nHost: 0.0.0.0:7000\r\nContent-Length: 23351\r\nConnection: keep-alive\r\n\r\n', _hasBody: true, _trailer: '', finished: true, _hangupClose: false, socket: [Circular], connection: [Circular], agent: [Object], socketPath: undefined, method: 'POST', path: '/doc', _headers: [Object], _headerNames: [Object], parser: [Object], res: [Circular] }, ondata: [Function: socketOnData] }, _consuming: true, _dumped: false, httpVersionMajor: 1, httpVersionMinor: 1, upgrade: false, req: { domain: null, _events: { error: [Object], response: [Function] }, _maxListeners: 10, output: [], outputEncodings: [], writable: true, _last: false, chunkedEncoding: false, shouldKeepAlive: true, useChunkedEncodingByDefault: true, sendDate: false, _headerSent: true, _header: 'POST /doc HTTP/1.1\r\ncontent-type: multipart/form-data; boundary=--------------------------994987473640480876924123\r\nHost: 0.0.0.0:7000\r\nContent-Length: 23351\r\nConnection: keep-alive\r\n\r\n', _hasBody: true, _trailer: '', finished: true, _hangupClose: false, socket: { _connecting: false, _handle: [Object], _readableState: [Object], readable: true, domain: null, _events: [Object], _maxListeners: 10, _writableState: [Object], writable: true, allowHalfOpen: false, onend: [Function: socketOnEnd], destroyed: false, bytesRead: 587, _bytesDispatched: 23536, _pendingData: null, _pendingEncoding: '', parser: [Object], _httpMessage: [Circular], ondata: [Function: socketOnData] }, connection: { _connecting: false, _handle: [Object], _readableState: [Object], readable: true, domain: null, _events: [Object], _maxListeners: 10, _writableState: [Object], writable: true, allowHalfOpen: false, onend: [Function: socketOnEnd], destroyed: false, bytesRead: 587, _bytesDispatched: 23536, _pendingData: null, _pendingEncoding: '', parser: [Object], _httpMessage: [Circular], ondata: [Function: socketOnData] }, agent: { domain: null, _events: [Object], _maxListeners: 10, options: {}, requests: {}, sockets: [Object], maxSockets: 5, createConnection: [Function] }, socketPath: undefined, method: 'POST', path: '/doc', _headers: { 'content-type': 'multipart/form-data; boundary=--------------------------994987473640480876924123', host: '0.0.0.0:7000', 'content-length': 23351 }, _headerNames: { 'content-type': 'content-type', host: 'Host', 'content-length': 'Content-Length' }, parser: { _headers: [], _url: '', onHeaders: [Function: parserOnHeaders], onHeadersComplete: [Function: parserOnHeadersComplete], onBody: [Function: parserOnBody], onMessageComplete: [Function: parserOnMessageComplete], socket: [Object], incoming: [Circular], maxHeaderPairs: 2000, onIncoming: [Function: parserOnIncomingClient] }, res: [Circular] }, pipe: [Function], addListener: [Function], on: [Function], pause: [Function], resume: [Function], read: [Function] } ```
2014/06/25
[ "https://Stackoverflow.com/questions/24411934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2263135/" ]
Look closely at this expression: ``` $('#searchResults').append(htmlifyResultsRow(data[i]), i) ``` You are passing `i` to `.append()`, not to `htmlifyResultsRow()`. This is why `i` is `undefined` in your `htmlifyResultsRow` function, because it is never passed a value for `i` in the first place. What you're probably looking to do is: ``` $('#searchResults').append(htmlifyResultsRow(data[i], i)) ```
60,007,527
e.g. ``` const char* my_func_string = "int func(){" " return 1; }"; //is there a way to do it automatically? int func(){ return 1; } ``` func could be of multiple lines. And I want my\_func\_string to capture the change whenever I change func. It'd be better if it's captured at compile time because the executables may not find the source code
2020/01/31
[ "https://Stackoverflow.com/questions/60007527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8984267/" ]
You could define the defaults within the function and use the [spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#Spread_in_object_literals) to combine the two objects, which will override the defaults where applicable. ```js function search(filterOptions) { const defaults = { foo: 'foo', foo2: 'bar' }; filterOptions = {...defaults,...filterOptions}; console.log(filterOptions); } search({foo: 'something'}); ```
31,263,203
I want to encapsulate global variables in a single "data-manager-module". Access is only possible with functions to avoid all the ugly global variable problems ... So the content is completely hidden from the users. Are there any existing concepts? How could such an implementation look like? How should the values stored in the "data-manager-module"?
2015/07/07
[ "https://Stackoverflow.com/questions/31263203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5088471/" ]
A "data manager module" doesn't make any sense. Implementing one would merely be sweeping away a fundamentally poor program design underneath the carpet, hiding it instead of actually cleaning it up. The main problem with globals is not user-abuse, but that they create tight couplings between modules in your project, making it hard to read and maintain, and also increases the chance of bugs "escalating" outside the module where the bug was located. Every datum in your program belongs to a certain module, where a "module" consists of a h file and a corresponding c file. Call it module or class or ADT or whatever you like. Common sense and OO design both dictate that the variables need to be declared in the module where they actually belong, period. You can either do so by declaring the variable at file scope `static` and then implement setter/getter functions. This is "poor man's private encapsulation" and not thread-safe, but for embedded systems it will work just fine in most cases. This is the embedded industry de facto standard of declaring such variables. Or alternatively and more advanced, you can do true private encapsulation by declaring a struct as incomplete type in a h file, and define it in the C file. This is sometimes called "opaque type" and gives true encapsulation on object basis, meaning that you can declare multiple instances of the class. Opaque type can also be used to implement inheritance (though in rather burdensome ways).
58,743,518
I' fetching data from axios through my API but when I'm rendering the data of it so it shows me blank template. So kindly let me know if I'm doing any mistake. I pasted my code with api response. Thanks console.log => response.data ``` Data Array [ Object { "ID": 2466, "ItemName": "WWE2K20" } ] ``` My Component ``` import React, { Component } from 'react'; import { Container, Header, Content, Card, CardItem, Body, Text } from 'native-base'; import { View, StyleSheet, FlatList, Image } from 'react-native'; import axios from 'axios'; export default class HomeScreen extends Component { constructor() { super() this.state = { itemList: [] } } async componentDidMount() { await axios.get('myapiuri') .then((response) => { this.setState({ itemList: response.data }); console.log("Data", this.state.itemList) }) .catch(error=>console.log(error)) } render() { return ( <Container> <Content> <FlatList data={this.state.itemList} renderItem={(item) => { return( <Text>{item.ItemName}</Text> ); }} keyExtractor={(item) => item.ID} /> </Content> </Container> ); } } ```
2019/11/07
[ "https://Stackoverflow.com/questions/58743518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8923126/" ]
There are a few problems I see. First you need to use ({item}) in renderItem as stated in comments. Second, you are mixing async/await with then block. In this case there is no need to async/await. So your code must be: ``` export default class HomeScreen extends Component { constructor() { super(); this.state = { itemList: [] }; } componentDidMount() { axios .get("myapiuri") .then(response => { this.setState({ itemList: response.data }); console.log("Data", this.state.itemList); }) .catch(error => console.log(error)); } render() { return ( <Container> <Content> <FlatList data={this.state.itemList} renderItem={({ item }) => { return <Text>{item.ItemName}</Text>; }} keyExtractor={item => item.ID} /> </Content> </Container> ); } } ``` If you still having problems, please look at this example: <https://snack.expo.io/@suleymansah/c0e4e5>
49,924,634
``` data = pd.read_csv("file.csv") As = data.groupby('A') for name, group in As: current_column = group.iloc[:, i] current_column.iloc[0] = np.NAN ``` The problem: 'data' stays the same after this loop, even though I'm trying to set values to np.NAN .
2018/04/19
[ "https://Stackoverflow.com/questions/49924634", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1525654/" ]
The simple answer is that, as indicated in the above quote from the mongo documenation, "different drivers might vary". In this case the default for mongolite is 5 minutes, found in [this](https://github.com/jeroen/mongolite/issues/34) github issue, I'm guessing it's related to the C drivers. > > The default socket timeout for connections is 5 minutes. This means > that if your MongoDB server dies or becomes unavailable it will take 5 > minutes to detect this. You can change this by providing > sockettimeoutms= in your connection URI. > > > Also noted in the github issue is a solution which is to increase the `sockettimeoutms` in the URI. At the end of the connection URI you should add `?sockettimeoutms=1200000` as an option to increase the length of time (20 minutes in this case) before a socket timeout. Modifying the original example code: ``` library(mongolite) mongo <- mongo(collection,url = paste0("mongodb://", user,":",pass, "@", mongo_host, ":", port,"/",db,"?sockettimeoutms=1200000")) mongo$find(fields = '{"sample_id":1,"_id":0}') ```
58,859,720
i need to send email when the ticket saves but am getting the error am guessing am supposed to put the values in array is my syntax okay? **ErrorException Undefined variable: userName** This is the store function ``` public function store(Request $request) { // Create Ticket $ticket=new Ticket; $ticket->userName= $request->input('userName'); $ticket->userEmail= $request->input('userEmail'); $ticket->phoneNumber= $request->input('phoneNumber'); $ticket->regular_quantity= $request->input('regular_quantity'); $ticket->vip_quantity= $request->input('vip_quantity'); $ticket->event_id=$request->route('id'); $ticket->total= $request->input('regular_quantity') + $request->input('vip_quantity'); $event = Event::find($ticket->event_id); if ($ticket->regular_quantity < $event->regular_attendies && $ticket->vip_quantity < $event->vip_attendies) { if($event->regular_attendies>0 && $event->vip_attendies>0){ DB::table('events')->decrement('regular_attendies', $ticket->regular_quantity); DB::table('events')->decrement('vip_attendies', $ticket->vip_quantity); $ticket->save(); $to_name = '$userName'; $to_email = '$userEmail'; $data = array('name'=>"$userName", "body" => "Test mail"); Mail::send('layouts.mail', $data, function($message) use ($to_name,$to_email){ $message->to('$userEmail'); $message->subject('Ticket success'); $message->from('kisilamapeni@gmail.com','kisila'); }); echo "Email sent"; } else{ echo"no available space"; } return redirect('/'); } } ```
2019/11/14
[ "https://Stackoverflow.com/questions/58859720", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Not sure what you're trying to do here. ``` $to_name = '$userName'; $to_email = '$userEmail'; ``` Setting `$to_name` to `'$userName'` will result in the string `'$userName'`, which seems pointless. Also, you're getting an error in this line: ``` $data = array('name'=>"$userName", "body" => "Test mail"); ``` When you wrap a variable in `" "`, it tries to parse it, but you don't have a variable `$username`. An easier way to accomplish this is to ignore setting these values and simply pass the newly created `$ticket` to your email, and reference the correct parameters: ``` $data = array("name" => $ticket->userName, "body" => "Test mail"); Mail::send("layouts.mail", $data, function($message) use ($ticket){ $message->to($ticket->userEmail); $message->subject("Ticket success"); $message->from('kisilamapeni@gmail.com','kisila'); }); ```
68,230,934
I have a script that constantly adds data to a dictionary(cannot be changed meaning no lists or to stop adding the data). It can easily reach over 1000 different keys within it. I require each key and value but don't want to reset the dictionary `foo`. ```py foo = {"369610": "a", "109122": "a", "907897": "a", "333291":"a", "381819": "a", "387583": "a", "677430": "a", "660221": "a", "118095":"a", "612172": "a"} print(len(foo)) # At 10 foo["223533"] = "a" # Replaces 369610 in the dictionary foo["601336"] = "a" # Replaces 109122 in the dictionary print(len(foo)) # Should be 10 ``` If I was to add more keys to the dictionary, it would replace 907897 then 333291 then 381819 and then 387583. Once it reaches the limit of 10 any more added would replace the first index 223533. I still want to access each value of each key as to why this is a dictionary and not a list. I have thought to iterate over the dictionary then get each entry and overwrite that one with: ```py del foo[index] foo[random.randint(5000,100000)] = "a" ``` But I feel like this is an inefficient solution.
2021/07/02
[ "https://Stackoverflow.com/questions/68230934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11603043/" ]
``` from collections import OrderedDict class FooDict(OrderedDict): def __init__(self, maxsize=5, /, *args, **kwds): self.maxsize = maxsize super().__init__(*args, **kwds) def __getitem__(self, key): value = super().__getitem__(key) return value def __setitem__(self, key, value): super().__setitem__(key, value) if len(self) > self.maxsize: oldest = next(iter(self)) del self[oldest] ``` ``` foo = FooDict() for i in range(10): foo[random.randint(5000,100000)] = "a" print(foo) FooDict([(82596, 'a')]) FooDict([(82596, 'a'), (67860, 'a')]) FooDict([(82596, 'a'), (67860, 'a'), (13232, 'a')]) FooDict([(82596, 'a'), (67860, 'a'), (13232, 'a'), (45835, 'a')]) FooDict([(82596, 'a'), (67860, 'a'), (13232, 'a'), (45835, 'a'), (15591, 'a')]) FooDict([(67860, 'a'), (13232, 'a'), (45835, 'a'), (15591, 'a'), (36689, 'a')]) FooDict([(13232, 'a'), (45835, 'a'), (15591, 'a'), (36689, 'a'), (60175, 'a')]) FooDict([(45835, 'a'), (15591, 'a'), (36689, 'a'), (60175, 'a'), (87882, 'a')]) FooDict([(15591, 'a'), (36689, 'a'), (60175, 'a'), (87882, 'a'), (59414, 'a')]) FooDict([(36689, 'a'), (60175, 'a'), (87882, 'a'), (59414, 'a'), (87218, 'a')]) ```
1,665,208
I have a partial view with a dropdown (with `Paid and unpaid` as options) and a button. I am loading this partial view using jquery load, when the user click `Paid/Unpaid List link` in the sub menu of a page. When i select Paid in dropdown and click the button, it shows the list of paid customers in the jquery dialog and if i select Unpaid and click button, it shows unpaid customers in the jquery dialog. I am writing the following code for the dialog: ``` $('#customers').dialog({ bgiframe: true, autoOpen: false, open: function(event, ui) { //populate table var p_option = $('#d_PaidUnPaid option:selected').val(); if (p_option == 'PAID') { $("#customercontent").html(''); //$("#customercontent").load("/Customer/Paid"); } else if (p_option == 'UNPAID') { $("#customercontent").html(''); //$("#customercontent").load("/Customer/Unpaid"); } }, close: function(event, ui) { //do nothing }, height: 500, width: 550, modal: true }); ``` For the first time, i am getting the list correctly in the jquery dialog, but when i click the `Paid/Unpaid List link` again and select Unpaid in the dropdown and click the button, it shows the previos loaded content in the jquery dialog. What am i doing wrong here?
2009/11/03
[ "https://Stackoverflow.com/questions/1665208", "https://Stackoverflow.com", "https://Stackoverflow.com/users/111435/" ]
Try adding no-caching option to jQuery AJAX. I had problems with the load() function (and IE) where cached results would always be shown. To change the setting for all jQuery AJAX requests do ``` $.ajaxSetup({cache: false}); ```
4,697,088
How does php access a variable passed by JQuery? I have the following code: ``` $.post("getLatLong.php", { latitude: 500000}, function(data){ alert("Data Loaded: " + data); }); ``` but I don't understand how to access this value using php. I've tried ``` $userLat=$_GET["latitude"]; ``` and ``` $userLat=$_GET[latitude]; ``` and then I try to print out the value (to check that it worked) using: `echo $userLat;` but it does not return anything. I can't figure out how to access what is being passed to it.
2011/01/14
[ "https://Stackoverflow.com/questions/4697088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/258755/" ]
$\_GET is for url variables (?latitude=bla), what you want is .. ``` $_POST['latitude'] ```
5,159
I have taken a look at the [list of recently migrated Arduino questions](https://electronics.stackexchange.com/search?tab=newest&q=arduino%20migrated%3ayes). I thought we had reached the consensus that questions regarding Arduino that involve a good deal of electronics are fine on this site. But I still see many questions migrated. * [ATMega328P-PU and 328P-AU](https://electronics.stackexchange.com/posts/158962/revisions) about differences between ATMega chips, not specifically in Arduinos * [What bytes do I send to the MAX7221 to light an LED (in an led Matrix)?](https://electronics.stackexchange.com/posts/158868/revisions) about interfacing a non-Arduino chip, which happens to be done with an Arduino * [Arduino - millis()](https://electronics.stackexchange.com/posts/158323/revisions) about C, which happens to be about a function from the Arduino libraries but also applies in many other cases * [Arduino/C++ byte manipulation](https://electronics.stackexchange.com/posts/160146/revisions) has nothing to do with Arduino: simple C - if anywhere, it should've been migrated to SO I would like to do a **general suggestion** that if the **community agrees** according to vote counts on this question and its answers, **this type of questions be no longer migrated** or only if there seems to be support from the community (other than only from one or two). As a moderator you're still part of the community and there is no reason to migrate away the questions you don't like if there's no support for this within the community. Update ====== This question, [Operate Arduino Nano using variable voltage](https://electronics.stackexchange.com/q/160323/17592), was first migrated to Arduino. I had to flag it there to get it migrated back here. Such moving around of posts isn't be beneficial to anyone. **NB**: (without sufficient rep?) you won't see this in the post history, but it's really true. I flagged the post on Arduino.SE and asked for a migration back. Related: [Can we stop the random migrating?](https://electronics.meta.stackexchange.com/q/5149/17592); +22/-5; not a duplicate since this is a general request (which the other was as well actually, but this was massively misunderstood, even after emphasising that aspect of the question).
2015/03/15
[ "https://electronics.meta.stackexchange.com/questions/5159", "https://electronics.meta.stackexchange.com", "https://electronics.meta.stackexchange.com/users/-1/" ]
Part of the reason why (I think) migrations are so frustrating from a community perspective is that there is no recourse if the community disagrees with the migration. In fact, the only way to undo a migration is to coordinate with the moderators of the target site to close the question, and then it can be "bounced back" to the original site. This makes migrations an unchangeable moderator action, instead of a normal close vote. I started asking myself *"How many bad migrations are we getting?"*, as that really sets the tone of this discussion. Here are some numbers to bring facts into the discussion. In the last 90 days, 78 questions have been migrated to Arduino.SE. Of those 78 questions, 4 have been rejected. While that sounds like a good number, it's worth noting that there are some different dynamics on Arduino.SE in the sense that they are a smaller beta site and don't quite have the numbers required to close questions by community. This is part of the reason why migrations to relatively new sites is discouraged - they don't have as much capability to deal with bad questions. Below is a list of questions migrated to Arduino.se in the last 90 days or so. This is not all of them as I seem to have missed some, but it's most of them (and I didn't intentionally omit questions). Some of them are deleted. From the perspective of migrating solid EE questions with a hint of Arduino, it doesn't seem so bad at first glance. <https://electronics.stackexchange.com/questions/160389/saving-arduino-output-to-a-text-file-in-append-mode?noredirect=1> <https://electronics.stackexchange.com/questions/160412/gsm-modem-with-max232-to-arduino-serial?noredirect=1> <https://electronics.stackexchange.com/questions/160255/how-to-do-serial-monitor-with-arduino-yun?noredirect=1> <https://electronics.stackexchange.com/questions/160269/seeedstudio-wifi-shield-v1-1-not-working-with-arduino-mega-2560?noredirect=1> <https://electronics.stackexchange.com/questions/160146/arduino-c-byte-manipulation?noredirect=1> <https://electronics.stackexchange.com/questions/159998/anakog-input-not-going-zero?noredirect=1> <https://electronics.stackexchange.com/questions/160005/ethernet-shield-not-getting-ip?noredirect=1> <https://electronics.stackexchange.com/questions/159960/arduino-unstable-analog-reading-when-using-power-supply?noredirect=1> <https://electronics.stackexchange.com/questions/159910/operate-arduino-nano-using-variable-voltage?noredirect=1> <https://electronics.stackexchange.com/questions/159789/using-an-arduino-uno-to-program-a-standalone-atmega2560?noredirect=1> <https://electronics.stackexchange.com/questions/159761/arduino-mega-number-of-simultaneous-pulse-inputs?noredirect=1> <https://electronics.stackexchange.com/questions/157859/is-it-possible-to-connect-many-arduino-uno-in-one-pc?noredirect=1> <https://electronics.stackexchange.com/questions/158962/atmega328p-pu-and-328p-au?noredirect=1> <https://electronics.stackexchange.com/questions/158940/arduino-sainsmart-uno-communication-problem?noredirect=1> <https://electronics.stackexchange.com/questions/158868/what-bytes-do-i-send-to-the-max7221-to-light-an-led-in-an-led-matrix?noredirect=1> <https://electronics.stackexchange.com/questions/158323/arduino-millis?noredirect=1> <https://electronics.stackexchange.com/questions/157919/arduino-how-to-accept-user-input-array-variables?noredirect=1> <https://electronics.stackexchange.com/questions/156885/how-best-to-power-down-an-arduino-for-5-minutes-at-a-time?noredirect=1> <https://electronics.stackexchange.com/questions/157704/stepper-motor-controller-using-leonardo-pro-micro?noredirect=1> <https://electronics.stackexchange.com/questions/157370/arduino-based-solid-state-drive?noredirect=1> <https://electronics.stackexchange.com/questions/157306/need-help-with-on-off-switch-to-power-arduino?noredirect=1> <https://electronics.stackexchange.com/questions/157029/which-components-to-built-remapping-keyboard-via-usb-in-out-remapped?noredirect=1> <https://electronics.stackexchange.com/questions/156741/gps-skm53-arduino-not-worcking?noredirect=1> <https://electronics.stackexchange.com/questions/156558/arduino-dimmer-shield-schematics-interpretation?noredirect=1> <https://electronics.stackexchange.com/questions/156360/programing-other-atmel-arm-chips-using-arduino?noredirect=1> <https://electronics.stackexchange.com/questions/155797/arduino-like-boards-with-other-microcontrollers?noredirect=1> --- Most questions have been automatically deleted at this point (about 30 days) --- <https://electronics.stackexchange.com/questions/149276/arduino-based-home-automation-system?noredirect=1> <https://electronics.stackexchange.com/questions/154173/error-code-10-for-arduino-device-driver?noredirect=1> <https://electronics.stackexchange.com/questions/154138/how-can-i-connect-the-canon-printer-8-pin-wifi-connector-to-arduino?noredirect=1> <https://electronics.stackexchange.com/questions/154078/should-i-use-an-arduino-or-not?noredirect=1> <https://electronics.stackexchange.com/questions/153435/two-arduinos-send-data-via-analog-pin?noredirect=1> <https://electronics.stackexchange.com/questions/153161/one-ftdi-on-three-atmega?noredirect=1> <https://electronics.stackexchange.com/questions/153073/servo-buzz-millis?noredirect=1> <https://electronics.stackexchange.com/questions/153023/which-arduino-to-choose-nano-micro-or-micro-pro?noredirect=1> <https://electronics.stackexchange.com/questions/152417/how-do-i-write-a-debugger-for-arduino?noredirect=1> <https://electronics.stackexchange.com/questions/152402/set-arduino-digitalread-reference-voltage?noredirect=1> <https://electronics.stackexchange.com/questions/151410/nrf24l01with-arduino-and-multiple-servos?noredirect=1> <https://electronics.stackexchange.com/questions/151062/how-can-i-make-pinmode-calls-faster?noredirect=1> <https://electronics.stackexchange.com/questions/150898/how-to-remove-adafruit-pro-trinket-bootloader-flashing-startup-sequence?noredirect=1> <https://electronics.stackexchange.com/questions/150755/how-do-i-replace-a-burnt-atmega328-with-a-new-atmega328bootloaded-in-arduino?noredirect=1> <https://electronics.stackexchange.com/questions/150475/arduino-uno-r3-not-recognized-by-computer-tx-and-rx-not-blinking-neither-are-l?noredirect=1> <https://electronics.stackexchange.com/questions/150417/connecting-relay-to-arduino-another-issue?noredirect=1> <https://electronics.stackexchange.com/questions/150313/how-are-arduinos-osh-if-atmel-avr-is-proprietary?noredirect=1> <https://electronics.stackexchange.com/questions/150290/replacing-the-voltage-regulator-of-a-fried-arduino?noredirect=1> <https://electronics.stackexchange.com/questions/150207/how-to-implement-an-arduiono-prototype?noredirect=1> <https://electronics.stackexchange.com/questions/150239/is-this-bluetooth-module-cool-for-arduino?noredirect=1> <https://electronics.stackexchange.com/questions/150163/arduino-cannot-communicate-with-pc-after-running-servo?noredirect=1> <https://electronics.stackexchange.com/questions/149961/program-read-93lc46b-with-an-arduino-with-bit-banging?noredirect=1> <https://electronics.stackexchange.com/questions/149890/turn-arduino-into-a-bootstrap-loader-for-msp430-programming?noredirect=1> <https://electronics.stackexchange.com/questions/149839/driving-conveyor-belts-using-arduino-unos?noredirect=1> <https://electronics.stackexchange.com/questions/149862/arduino-serial-hex-values?noredirect=1> <https://electronics.stackexchange.com/questions/149862/arduino-serial-hex-values?noredirect=1> <https://electronics.stackexchange.com/questions/149819/why-doesnt-this-motor-turn?noredirect=1> <https://electronics.stackexchange.com/questions/149295/dhcpaddressprinter-example-has-no-output-in-serial-monitor?noredirect=1> <https://electronics.stackexchange.com/questions/148090/arduino-two-ethernet-shields?noredirect=1> <https://electronics.stackexchange.com/questions/146752/are-there-any-kl03-arduinos?noredirect=1> <https://electronics.stackexchange.com/questions/146205/how-to-connect-gsm-with-arduino-and-dialling-number-from-hex-kepad?noredirect=1> <https://electronics.stackexchange.com/questions/146116/light-led-when-2-others-are-disconnected?noredirect=1> <https://electronics.stackexchange.com/questions/145971/arduino-power-consumption-issues?noredirect=1> <https://electronics.stackexchange.com/questions/145850/help-with-parts-identification-from-arduino-starter-kit-from-aliexpress?noredirect=1> <https://electronics.stackexchange.com/questions/145488/powering-arduino-from-a-shield?noredirect=1> <https://electronics.stackexchange.com/questions/145463/arduino-wifi-shield-not-present-error?noredirect=1> <https://electronics.stackexchange.com/questions/145330/can-an-arduino-micro-recieve-commands-from-another-microcontroller-when-hardwire?noredirect=1> <https://electronics.stackexchange.com/questions/145258/raspberry-pi-with-arduino-serial-connection-stops-working?noredirect=1> <https://electronics.stackexchange.com/questions/145023/controlling-arduino-from-raspberry-pi?noredirect=1>
52,670,062
I am using Gradle 4.1 with Gradle-Android plugin 3.0.1 on Android Studio 3.2 I have 2 flavors 'production' and 'staging' and I am unable to build my project as a library with different build variants. **app build.gradle:** ``` apply plugin: 'com.android.library' apply plugin: 'com.github.dcendents.android-maven' android { ... productFlavors { production { } staging { } } defaultPublishConfig "productionRelease" publishNonDefault true } if( android.productFlavors.size() > 0 ) { android.libraryVariants.all { variant -> if( android.publishNonDefault && variant.name == android.defaultPublishConfig ) { def bundleTask = tasks["bundle${name.capitalize()}"] artifacts { archives(bundleTask.archivePath) { classifier name.replace('-' + variant.name, '') builtBy bundleTask name name.replace('-' + variant.name, '') } } } ``` ... Then I run: ./gradlew clean install, errors I got is: Execution failed for task ‘:app:install’. > > Could not publish configuration ‘archives’ > A POM cannot have multiple artifacts with the same type and classifier. Already have MavenArtifact app:aar:aar:null, trying to add MavenArtifact app:aar:aar:null. > > > And to get this code to compile, I need to swap **android.publishNonDefault** with **true**, otherwise I will get an error of: `Cannot get the value of write-only property 'publishNonDefault'` Any suggestions or hint would be really helpful, the aim is to build the library module on jitpack, where we can import it in project with build variants. thanks!
2018/10/05
[ "https://Stackoverflow.com/questions/52670062", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2099298/" ]
After digging into this for 2 days, and emailing Jitpack support, the issue is because the lib has updated and **publishNonDefault** is deprecated. you just need to change your app build.gradle to: ``` apply plugin: 'com.github.dcendents.android-maven' dependencies {...} group = 'com.github.your-group' if (android.productFlavors.size() > 0) { android.libraryVariants.all { variant -> if (variant.name.toLowerCase().contains("debug")) { return } def bundleTask = tasks["bundle${variant.name.capitalize()}"] artifacts { archives(bundleTask.archivePath) { classifier variant.flavorName builtBy bundleTask name = project.name } } } } ```
901,190
I'm trying to enable Windows Hyper-V replication over WAN. I have (finally!) been able to achieve this in a test environment over LAN using the certificate-based authentication method (rather than Kerberos) and have been able to successfully get two servers to replicate using the hostname. My confusion now is that I do not know how to get them to communicate over the WAN for the purpose of replication. In production, I currently have one server (Win 2012 R2) sat in a datacentre and the intention is to spin up another server to take the replication, but this will be in another datacentre, connected only via the internet using external IP addresses. There is no active directory in place, they are just in a workgroup. I'd rather not set up AD or DC just for this (unless I really have to). I already have an A record pointing towards the server (via our domain names provider), so it has an entry in the form of server1.domain.com. So I have server1.domain.com pointing to external IP address, which reaches the server correctly. In a test environment, this is what I have done so far. Both servers are Windows 2012 R2. Server 1 is the main host server with a number of VM's, it's named SERVER1 (Computer Name) Server 2 has been spun up to take the replication of the VM's from server 1, it's named SERVER2. They are currently connected internally only via internal network and internal IP addresses. As mentioned above, I have successfully achieved replication between SERVER1 and SERVER2 using certificate-based authentication and it works correctly, but this is using the computer name SERVER2 as a destination replication server. Obviously once this is in a production environment, this method will not be possible. My question is, how do I set this up so that SERVER1 can see SERVER2 across a WAN (for the purpose of Hyper-V replica) where there is no active directory. How will they resolve? Do I make an entry on the HOSTS file? If so, what should I enter? Is it as easy as SERVER1 External IP address of SERVER1 SERVER2 External IP address of SERVER2 Or do I point it to the FQDN (which is created as an A record) in the format: SERVER1 SERVER1.domain.com SERVER2 SERVER2.domain.com I'd appreciate any assistance on this as I'm currently a bit stuck and as I'm currently unable to test this is a live production environment I'd rather go in with as much knowledge as possible. Thank you.
2018/03/12
[ "https://serverfault.com/questions/901190", "https://serverfault.com", "https://serverfault.com/users/197330/" ]
I am afraid this not an answer to what you currently have. What you should be running for your configuration, (ie no AD, no shared storage)is a shared nothing configuration supported on Windows Server 2016. <https://social.technet.microsoft.com/Forums/windows/en-US/e14e7171-d8fb-418c-9e9e-b3883f4c4ea3/windows-2016-2node-shared-nothing-stretched-cluster-with-storage-replicas?forum=winserverClustering> <https://www.starwindsoftware.com/blog/part-2-storage-replica-with-microsoft-failover-cluster-and-scale-out-file-server-role-windows-server-technical-preview>
41,366,113
i made a query that shows the result i want (close enough)... but it's not perfect as should be. I'm counting the number of registers per user.. The SQL: ``` SELECT us.name, _reg FROM tb_user AS us LEFT JOIN tb_register as rg ON rg.iduser = us.iduser INNER JOIN (select rg.iduser, count(*) FROM tb_register AS rg group by rg.iduser) AS _reg ON rg.iduser = _reg.iduser GROUP BY us.name, _reg ``` The result i get is something like... ``` +-----------+-----------------+ | name | _reg | +-----------+-----------------+ | example_A | (id_A, count_A) | +-----------+-----------------+ | example_B | (id_B, count_B) | +-----------+-----------------+ ``` But what i really want is just name and the row count.. I'm using in the subquery "rg.iduser" to reference in this INNER JOIN, but because of that, i get the "iduser" in the result. **Is there a better way to do that to show what i want.. or a way to hide the "iduser" in the result of this query?** Thanks..
2016/12/28
[ "https://Stackoverflow.com/questions/41366113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6226487/" ]
Gordon's answer shows you a better way to do the query. But I'd like to explain *why* you are seeing both columns in the output: You are using the alias for the derived table `_reg` in the select list, which means you are retrieving every row from that derived table as an anonymous record. If you just want the count, then give that column a proper alias and reference the *column* in the outer select, not the *row*: Also the `group by` in the outer select seems useless: ``` SELECT us.name, **\_reg.cnt** --<< HERE FROM tb_user AS us LEFT JOIN tb_register as rg ON rg.iduser = us.iduser JOIN ( select rg.iduser, count(*) **as cnt** --<< HERE FROM tb_register AS rg group by rg.iduser ) AS _reg ON rg.iduser = _reg.iduser; ```
33,645
When looking at the [Gee Bee](https://en.wikipedia.org/wiki/Gee_Bee_Model_R): [![enter image description here](https://i.stack.imgur.com/AaprL.jpg)](https://i.stack.imgur.com/AaprL.jpg) [Source](http://photo.net/learn/airshow/GeeBee.html) I wonder what the pilot is actually able to see, when rolling on the runway, when flying level, or trying to locate a possible emergency landing place. It seems this aircraft puts the pilot and the people on the ground at risk. Wouldn't a mirror improve safety, or is there a hole in the bottom of the fuselage? How could such an aircraft be allowed to fly at the time? Did flying it only require to hold a recreational private pilot license or additional qualifications? Would it be allowed today in Europe, or in the US, based on existing regulation?
2016/12/04
[ "https://aviation.stackexchange.com/questions/33645", "https://aviation.stackexchange.com", "https://aviation.stackexchange.com/users/3201/" ]
At least it has a forward looking windshield. [![enter image description here](https://i.stack.imgur.com/3YuVf.jpg)](https://i.stack.imgur.com/3YuVf.jpg) ([Source](http://images.fineartamerica.com/images-medium-large/charles-lindbergh-flying-his-plane-everett.jpg)) *[Spirit of St. Louis](https://en.wikipedia.org/wiki/Spirit_of_St._Louis) that was flown solo by Charles Lindbergh on May 20–21, 1927, on the first solo non-stop transatlantic flight from Long Island, New York, to Paris, France.* [![enter image description here](https://i.stack.imgur.com/bNHUs.png)](https://i.stack.imgur.com/bNHUs.png) ([Source](http://www.charleslindbergh.com/plane/plane.gif)) [![enter image description here](https://i.stack.imgur.com/aT0yO.jpg)](https://i.stack.imgur.com/aT0yO.jpg) ([Source](https://aviation.stackexchange.com/a/26052)) *A 777-300 [needs a camera](https://aviation.stackexchange.com/a/26052) too to make cornering easier.* Like all tail-draggers, the pilot can be guided by a wing-sitter, or by taxiing in an S-shape. For landing, a little cross-control to crab will allow a side view of what's ahead. Above methods were/are very common for WWII-era planes with huge noses and a tail-dragger undercarriage. [![enter image description here](https://i.stack.imgur.com/e3i31m.png)](https://i.stack.imgur.com/e3i31.png) [![enter image description here](https://i.stack.imgur.com/Y3V6Km.jpg)](https://i.stack.imgur.com/Y3V6K.jpg) ([Left](http://www.354thpmfg.com/aircraft_p47thunderbolt.html), [right](https://i.pinimg.com/originals/51/dc/9a/51dc9a2af09949d3e03d7cd5ea42cff6.jpg)) Taxiing with wing-sitter assistance. Landing on big grass-fields makes it easier too. > > Would the Gee Bee be allowed to fly today? > > > The [Gee Bee](https://en.wikipedia.org/wiki/Gee_Bee_Model_R) was still flying airshows until 2002, so the answer is yes. [![enter image description here](https://i.stack.imgur.com/YmBlh.jpg)](https://i.stack.imgur.com/YmBlh.jpg) ([Source](https://en.wikipedia.org/wiki/File:GeeBee_R2_Oshkosh.jpg)) *Gee Bee R2 flown by Delmar Benjamin at Oshkosh 2001. Benjamin flew an aerobatic routine in this aircraft at numerous airshows until he retired the aircraft in 2002.*
52,430,353
``` using System; class MainClass { public static void Main (string[] args) { bool loop1 = true; while(loop1) { Console.WriteLine("\nEnter the base length"); try { int length = Convert.ToInt32(Console.ReadLine()); } catch (Exception ex) { Console.WriteLine("\nInvalid Entry: "+ex.Message); continue; } Console.WriteLine("\nEnter the perpendicular height"); try { int length = Convert.ToInt32(Console.ReadLine()); } catch (Exception ex) { Console.WriteLine("\nInvalid Entry: "+ex.Message); } Console.WriteLine(area(length,height)); } } static int area(int length, int height) { return length * height/2; } } ``` I get the error > > exit status 1 > main.cs(28,40): error CS0103: The name `length' does not exist in the current context > main.cs(28,47): error CS0103: The name`height' does not exist in the current context > Compilation failed: 2 error(s), 0 warnings > > >
2018/09/20
[ "https://Stackoverflow.com/questions/52430353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10392786/" ]
You are declaring your variables inside the try, you need to move the declaration outside the try statement. I think this will fix it. Plus your declaring length twice, I think that was a typo and should have been height. ``` using System; class MainClass { public static void Main (string[] args) { int length = 0; int height = 0; bool loop1 = true; while(loop1) { Console.WriteLine("\nEnter the base length"); try { length = Convert.ToInt32(Console.ReadLine()); } catch (Exception ex) { Console.WriteLine("\nInvalid Entry: "+ex.Message); continue; } Console.WriteLine("\nEnter the perpendicular height"); try { height = Convert.ToInt32(Console.ReadLine()); } catch (Exception ex) { Console.WriteLine("\nInvalid Entry: "+ex.Message); } Console.WriteLine(area(length,height)); }// end while }// end main static int area(int length, int height) { return length * height/2; } }// end calss ```
50,174,204
I have [consul](https://hub.docker.com/_/consul/) and [registrator](http://gliderlabs.github.io/registrator/latest/) running. I can start services in docker containers: ``` docker run -d -P --name=redis redis ``` And `registrator` is, as expected, able to register the services in `consul`: ``` http http://localhost:8500/v1/catalog/service/redis HTTP/1.1 200 OK Content-Encoding: gzip Content-Length: 308 Content-Type: application/json Date: Fri, 04 May 2018 11:33:50 GMT Vary: Accept-Encoding X-Consul-Effective-Consistency: leader X-Consul-Index: 34 X-Consul-Knownleader: true X-Consul-Lastcontact: 0 [ { "Address": "127.0.0.1", "CreateIndex": 34, "Datacenter": "dc1", "ID": "48b6c821-3b93-dbf4-394e-5024123ea7df", "ModifyIndex": 34, "Node": "863e97e527c3", "NodeMeta": { "consul-network-segment": "" }, "ServiceAddress": "", "ServiceEnableTagOverride": false, "ServiceID": "polyphemus.wavilon.net:redis:6379", "ServiceMeta": {}, "ServiceName": "redis", "ServicePort": 32769, "ServiceTags": [], "TaggedAddresses": { "lan": "127.0.0.1", "wan": "127.0.0.1" } } ] ``` I can then use `consul` DNS services: ``` » dig @127.0.0.1 -p 8600 redis.service.consul ; <<>> DiG 9.10.3-P4-Ubuntu <<>> @127.0.0.1 -p 8600 redis.service.consul ; (1 server found) ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 62382 ;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1 ;; WARNING: recursion requested but not available ;; OPT PSEUDOSECTION: ; EDNS: version: 0, flags:; udp: 4096 ;; QUESTION SECTION: ;redis.service.consul. IN A ;; ANSWER SECTION: redis.service.consul. 0 IN A 127.0.0.1 ;; Query time: 0 msec ;; SERVER: 127.0.0.1#8600(127.0.0.1) ;; WHEN: Fri May 04 13:31:21 CEST 2018 ;; MSG SIZE rcvd: 65 ``` This is all fine. This basically means that I can start using consul to locate my services, so that something like this: ``` curl -X GET http://myservice.service.consul ``` Would work from inside my container. But ... there is one piece missing here: `registrator` is aware of the IP **and** the port where the service is running. I can check this via a special dns `SRV` request: ``` » dig @127.0.0.1 -p 8600 redis.service.consul SRV ; <<>> DiG 9.10.3-P4-Ubuntu <<>> @127.0.0.1 -p 8600 redis.service.consul SRV ; (1 server found) ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 52758 ;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 3 ;; WARNING: recursion requested but not available ;; OPT PSEUDOSECTION: ; EDNS: version: 0, flags:; udp: 4096 ;; QUESTION SECTION: ;redis.service.consul. IN SRV ;; ANSWER SECTION: redis.service.consul. 0 IN SRV 1 1 32769 863e97e527c3.node.dc1.consul. ;; ADDITIONAL SECTION: 863e97e527c3.node.dc1.consul. 0 IN A 127.0.0.1 863e97e527c3.node.dc1.consul. 0 IN TXT "consul-network-segment=" ;; Query time: 0 msec ;; SERVER: 127.0.0.1#8600(127.0.0.1) ;; WHEN: Fri May 04 13:36:02 CEST 2018 ;; MSG SIZE rcvd: 149 ``` My question is: how do I integrate this in my application? Let's say I am writing a `python` application using `requests`. How would DNS resolution locate and use the port that is being exposed by the service? To be clear: the information is properly registered in `consul`, how do I use this information from the application? I see different options: * implement a "consul DNS resolution" layer in my application (as a library), which makes `SRV` DNS (or API) requests to consul in order to locate IP and port. * force the containers to always expose port `80` (I am doing http REST services), so that DNS resolution does not need to care about the port. The first option implies some refactoring of the application, which I would like to avoid. The second option implies that I need to fiddle with all services configuration. Is there a better alternative? Is there a transparent way of integrating `SRV` DNS requests when doing name resolution, and automatically making use of the port instead of using port `80` (or `443`)? I do not see how this would be feasible at all with `python` `requests`, or with `curl`, or with any other tool: we always need to manually specify the port when using those libraries / tools. And a related question: when / how are `SRV` DNS requests used? It seems those provide exactly the information that I need, but normal DNS resolution does not make use of it: clients are always making assumptions about the port where the service is running (`80` for `http`, `443` for `https` and so on) instead of asking the DNS server, which has the information.
2018/05/04
[ "https://Stackoverflow.com/questions/50174204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/647991/" ]
Few ways in which we handled this problem: * Use a docker overlay network for container to container communication. In this case, your ports can be static (at the container level) and you can assume the port number while making connections * Use "consul-template" to generate a config file with IP and port info read from consul. This consul-template command will typically run as your docker entry point and will in turn launch your actual app. Whenever there is a change in consul, consul-template will regenerate the file and can be configured to reload/restart your app Thanks, Arul
68,496,205
I’m developing a new application in which I have to generate a unique custom serial number for each new invoice and I must have a counter for all of the invoices in the system. The format of the serial number is CCBBBYYYYNNNNNN. Where: * C = First two letters of the Company name * B = First three letters of the branch name * Y = Year No * N = Serial number from 000001 to 999999 I need your help to come up with a solution that will avoid any discrepancy in the serial numbers and can support multiple users at the same time. In addition, I need to create and save a counter for each newly-created invoice. How can I achieve this? What is the best way to do it through the database side or the application side? I also need to reset the serial number counter to zero at the beginning of every year.
2021/07/23
[ "https://Stackoverflow.com/questions/68496205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3885917/" ]
There is nothing special with array\_push in loop (You are using while loop) and initilizing values to an array (`$arr[] = $element`). The only differene is you are pushing value into the array through while loop and declaring initially using assignment operator. In your case, you have initilized $element to the array ``` $arr[] = "123"; //Lets say 123 is $element $arr[] = "NAME"; //Same way, you can repeat in next line as well $arr[] = "45"; echo '<pre>'; print_r($arr); // And the output was Array ( [0] => 123 [1] => NAME [2] => 45 ) ``` And the next statement was ``` while ($row = $result->fetch_assoc()) { $ids[] = $row['id'];// Lets say 123 is $row['id']; $names[] = $row['name']; //Lets say NAME is $row['name']; $ages[] = $row['age']; //Lets say 45 is $row['age']; } //The output will be same if only one row exist in the loop Array ( [0] => 123 [1] => NAME [2] => 45 .................. // Based on while loop rows ) ``` The symbol **[]** will push value into array because you didn't mention any key in between bracket.
29,946,395
I have an UITextField, at the end of the textfield I want to add an UIImage. When I put an UIImageView on top of the UITextField, the UIImageView is always (duh!) visible in top of the UITextField. What code do I need to write so that at the end of the text from the UITextField the UIImageView appears?
2015/04/29
[ "https://Stackoverflow.com/questions/29946395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4763956/" ]
No code needed, just add the proper constraints on the interface builder. Command-click to the image and bind it to the text field, then select horizontal (or vertical) spacing from the popup list.
34,525,650
I'm new to web front-end programming and am teaching myself AngularJS. I have created a very simple webapp that just lets users login and logout. I am running it locally on my Mac OSX. Below is my `index.html` file. Although it works, I'm not sure if I'm doing it right. I need to know how and where to import the angular.js files and the bootstrap.js files. My questions are as follows. I haven't been able to figure this stuff out by googling. I need someone to explain this stuff to me please. 1. I'm currently importing the `angular.js` file from `https://ajax.googleapis.com`. Is that correct? Or should I download it and store that file in the same directory as `index.html`? Why? When should I use the non-minified file? What is the benefit of using non-minified? 2. I'm currently not importing any bootstrap file(s). Which file(s) should I import? Should I import it/them as a URL or as a file from the same directory as `index.html` 3. For both Bootstrap and AngularJS, please tell me which line numbers I should put the `script src` lines in my HTML. 4. Should I check the Angular and Bootstrap files into my Github repository? index.html: ``` <html ng-app="app"> <head> </head> <body ng-controller="Main as main"> <input type="text" ng-model="main.username" placeholder="username"> <br> <input type="password" ng-model="main.password" placeholder="password"> <br> <br> <button ng-click="main.login()" ng-hide="main.isAuthed()">Login</button> <button ng-click="main.logout()" ng-show="main.isAuthed()">Logout</button> <br/> {{main.message}} <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0-beta.5/angular.min.js"></script> <script src="app.js"></script> </body> </html> ```
2015/12/30
[ "https://Stackoverflow.com/questions/34525650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1742777/" ]
Normally, you add CSS stylesheets and JS scripts in the `<head>`(between lines 2 and 3) area of your html. You can either link files with URLs like the example below or just download the whole Angular.js or Bootstrap.css file (both of them aren't that big) and put them in the same folder as your `index.html` file. URL/CDN example: ``` <head> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js"></script> </head> ``` Local folder example: ``` <head> <link rel="stylesheet" href="bootstrap.min.css"> <script type="text/javascript" src="angular.min.js"></script> </head> ``` Minified files (`angular.js` vs `angular.min.js`) will both run the same way. The only difference is the `.min.` file has the code all squished without any spaces, tabs, and new lines. This makes it load faster for computers, but if you're going to customize your angular or bootstrap in the future, you will find the squished format impossible to read. You don't need to be too concerned with doing everything 'the perfect way' if you're just starting out. I used to include the angular.js and bootstrap.css files along with my index.html in my project when I pushed it to Github. After a while though you might find it cleaner to leave them out and just use the URL-format. Some people will say you should put all your JS files and links at the bottom of your webpage (just before the `</body>` tag), but again this is just another optimization towards 'perfect' that you shouldn't worry too much about.
53,682,098
I have opened an Android Studio project which was created some time ago and the IDE says that a gradle plugin for Kotlin supports a Kotlin version 1.2.51 or higher. I would like to set it to the latest version but I have to go to the Kotlin website on which it's not easy to find out this information. Is it possible to find out the latest version of Kotlin in Android Studio?
2018/12/08
[ "https://Stackoverflow.com/questions/53682098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1180728/" ]
If you are on windows do the following: FILE > SETTINGS > LANGUAGE AND FRAMEWORK > KOTLIN UPDATES [![enter image description here](https://i.stack.imgur.com/I97f8.jpg)](https://i.stack.imgur.com/I97f8.jpg) then click on check and then if there was a newer version press install
11,914
Some people appear to be born with muscle\*. I know lots of people who don't work out at all, have an office job where they sit around all day, and still they have a muscular body with strong (looking) arms, big chest etc. Me, I'm naturally slim, and however hard I work out, I seem unable to make a big change in my physical appearance. Yes, I do get stronger and more fit, but I look (almost) the same after a year of intense training: thin. What can I do? Several years ago I did dumbell exercises from Bill Pearl's "Getting Stronger" and supplemented my diet with a meat based protein shake. After a year this made me look more toned, but the effect was minor. I stopped this routine when doing lunges with weights caused knee pain. At the moment I follow Mark Verstegen's "Core Performance" (the book), but have only been at it for a few months. I did not change my diet again except eat more soy products and nuts. The time is too short for any visible effects, of course. I'll very likely stop this routine also, because I'm experiencing shoulder pain from raining weights above shoulder height. I don't mean to imply that these routines don't work for me, I just describe what I did to give you an idea of the status quo - and of the fact that I easily self-hurt myself, if I work with weights. I don't want to go to a gym (for reasons that are irrelevant here but definite), so I cannot work out using machines. --- \*Obviously people are not literally "born with muscle". There is a genetic influence and, as has been found, the muscles that children use around 5 to 6 years of age develop in the adult individual. Both influences cannot be changed by a post-adolescent adult, so "born with muscle" is a good short description of the situation.
2013/03/14
[ "https://fitness.stackexchange.com/questions/11914", "https://fitness.stackexchange.com", "https://fitness.stackexchange.com/users/-1/" ]
Very few people are "born with muscle" to a degree that matters; they are possibly born with larger bone structures, or born with genes that make muscle gaining easier. One such gene would be the feeling of fullness -- some people have to eat more to feel full, and some less. However, if you've done a lot of heavy lifting via chores/physical tasks while growing up and still eat a lot, you will (slowly and inefficiently, but still surely) gain muscle. The unaccounted-for factor here is your diet. Lifting heavy, eating to calorie surplus, and eating large amounts of protein (try your body weight in grams, just to be sure) will make sure you make muscle gains. However, lifting heavy is not enough either: to stimulate hypertrophy (the growth of muscles), you should be lifting in the 8-12 rep range. Adjust weight (more or less) until you get there. To increase strength (absolute pounds lifted), lift in the 5-6 rep range.
20,746,940
I have floats like these, ``` 0.0 , 50.0 ... ``` How do I convert them to: ``` 0 , 50 ... ``` I need the meaningful numbers in the decimal part stay intact; so `13.59` must remain `13.59`. EDIT : my question is way different from that duplicate of yours; if only you read through it you would know it.
2013/12/23
[ "https://Stackoverflow.com/questions/20746940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3080376/" ]
Command `find_package` has two modes: `Module` mode and `Config` mode. You are trying to use `Module` mode when you actually need `Config` mode. ### Module mode `Find<package>.cmake` file located **within** your project. Something like this: ``` CMakeLists.txt cmake/FindFoo.cmake cmake/FindBoo.cmake ``` `CMakeLists.txt` content: ``` list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_LIST_DIR}/cmake") find_package(Foo REQUIRED) # FOO_INCLUDE_DIR, FOO_LIBRARIES find_package(Boo REQUIRED) # BOO_INCLUDE_DIR, BOO_LIBRARIES include_directories("${FOO_INCLUDE_DIR}") include_directories("${BOO_INCLUDE_DIR}") add_executable(Bar Bar.hpp Bar.cpp) target_link_libraries(Bar ${FOO_LIBRARIES} ${BOO_LIBRARIES}) ``` Note that `CMAKE_MODULE_PATH` has high priority and may be usefull when you need to rewrite standard `Find<package>.cmake` file. ### Config mode (install) `<package>Config.cmake` file located **outside** and produced by `install` command of other project (`Foo` for example). `foo` library: ``` > cat CMakeLists.txt cmake_minimum_required(VERSION 2.8) project(Foo) add_library(foo Foo.hpp Foo.cpp) install(FILES Foo.hpp DESTINATION include) install(TARGETS foo DESTINATION lib) install(FILES FooConfig.cmake DESTINATION lib/cmake/Foo) ``` Simplified version of config file: ``` > cat FooConfig.cmake add_library(foo STATIC IMPORTED) find_library(FOO_LIBRARY_PATH foo HINTS "${CMAKE_CURRENT_LIST_DIR}/../../") set_target_properties(foo PROPERTIES IMPORTED_LOCATION "${FOO_LIBRARY_PATH}") ``` By default project installed in `CMAKE_INSTALL_PREFIX` directory: ``` > cmake -H. -B_builds > cmake --build _builds --target install -- Install configuration: "" -- Installing: /usr/local/include/Foo.hpp -- Installing: /usr/local/lib/libfoo.a -- Installing: /usr/local/lib/cmake/Foo/FooConfig.cmake ``` ### Config mode (use) Use `find_package(... CONFIG)` to include `FooConfig.cmake` with imported target `foo`: ``` > cat CMakeLists.txt cmake_minimum_required(VERSION 2.8) project(Boo) # import library target `foo` find_package(Foo CONFIG REQUIRED) add_executable(boo Boo.cpp Boo.hpp) target_link_libraries(boo foo) > cmake -H. -B_builds -DCMAKE_VERBOSE_MAKEFILE=ON > cmake --build _builds Linking CXX executable Boo /usr/bin/c++ ... -o Boo /usr/local/lib/libfoo.a ``` Note that imported target is **highly** configurable. See my [answer](https://stackoverflow.com/a/20838147/2288008). **Update** * [Example](https://github.com/forexample/package-example)
71,709,360
I am following the NestJS fundamentals course and I am getting stuck with the "[Use transactions](https://learn.nestjs.com/courses/591712/lectures/23193771)" section: First of all, it seems to me that the course contains a typo in the import: ``` // ... other imports import { Entity } from '../events/entities/event.entity'; ``` Should be: `import { Event } ...` But then, after having completed the section, I realize that I have this compilation error: > > [Nest] 507493 - 04/01/2022, 5:13:17 PM ERROR [ExceptionHandler] No > repository for "Event" was found. Looks like this entity is not > registered in current "default" connection? RepositoryNotFoundError: > No repository for "Event" was found. Looks like this entity is not > registered in current "default" connection? > at RepositoryNotFoundError.TypeORMError [as constructor] (/home/vmalep/Dvpt/NestJS/course/iluvcoffee/src/error/TypeORMError.ts:7:9) > at new RepositoryNotFoundError (/home/vmalep/Dvpt/NestJS/course/iluvcoffee/src/error/RepositoryNotFoundError.ts:10:9) > at EntityManager.getRepository (/home/vmalep/Dvpt/NestJS/course/iluvcoffee/src/entity-manager/EntityManager.ts:964:19) > at Connection.getRepository (/home/vmalep/Dvpt/NestJS/course/iluvcoffee/src/connection/Connection.ts:354:29) > at InstanceWrapper.useFactory [as metatype] (/home/vmalep/Dvpt/NestJS/course/iluvcoffee/node\_modules/@nestjs/typeorm/dist/typeorm.providers.js:17:30) > at Injector.instantiateClass (/home/vmalep/Dvpt/NestJS/course/iluvcoffee/node\_modules/@nestjs/core/injector/injector.js:333:55) > at callback (/home/vmalep/Dvpt/NestJS/course/iluvcoffee/node\_modules/@nestjs/core/injector/injector.js:48:41) > at processTicksAndRejections (node:internal/process/task\_queues:96:5) > at Injector.resolveConstructorParams (/home/vmalep/Dvpt/NestJS/course/iluvcoffee/node\_modules/@nestjs/core/injector/injector.js:122:24) > at Injector.loadInstance (/home/vmalep/Dvpt/NestJS/course/iluvcoffee/node\_modules/@nestjs/core/injector/injector.js:52:9) > > > The code is available here: <https://github.com/vmalep/nestJSCourse/tree/useTransacionError> I have tried different solution, but to no avail and the course does not give any contact to get support (despite the fact that we have to pay for it...). So I am asking for help in this forum. It will be highly appreciated! Best regards, Pierre
2022/04/01
[ "https://Stackoverflow.com/questions/71709360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2865385/" ]
here's a 1 liner for this purpose using the Counter function from collections library: ``` from collections import Counter l = ['dog', 'bird', 'bird', 'cat', 'dog', 'fish', 'cat', 'cat', 'dog', 'cat', 'bird', 'dog'] print(Counter(l)) ```
593,092
I want to protect only certain numbers that are displayed after each request. There are about 30 such numbers. I was planning to have images generated in the place of those numerbers, but if the image is not warped as with captcha, wont scripts be able to decipher the number anyway? Also, how much of a performance hit would loading images be vs text?
2009/02/27
[ "https://Stackoverflow.com/questions/593092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49632/" ]
It's not possible. * You use javascript and encrypt the page, using document.write() calls after decrypting. I either scrape from the browser's display or feed the page through a JS engine to get the output. * You use Flash. I can poke into the flash file and get the values. You encrypt them in the flash and I can just run it then grab the output from the interpreter's display as a sequence of images. * You use images and I can just feed them through an OCR. You're in an arms race. What you need to do is make your information so useful and your pages so easy to use that you become the authority source. It's also handy to change your output formats regularly to keep up, but screen scrapers can handle that unless you make fairly radical changes. Radical changes drive users away because the page is continually unfamiliar to them. Your image solution wont' help much, and images are far less efficient. A number is usually only a few bytes long in HTML encoding. Images start at a few hundred bytes and expand to a 1k or more depending on how large you want. Images also will not render in the font the user has selected for their browser window, and are useless to people who use assisted computing devices (visually impaired people).
1,354,385
I am using VMware Workstation 14 Pro, and I'm trying to run a virtual machine that I've downloaded from Microsoft and saved to an external USB solid-state drive. But when I attempt to open that VM (by selecting File|Open and navigating to the path on that drive), I get an Import dialog. [![Import Dialog Box](https://i.stack.imgur.com/XViYg.png)](https://i.stack.imgur.com/XViYg.png) I don't want to import the VM. I already have a bunch of VMs running from my hard drive. I just want to run the VM from its current location. In years past, I always ran VMs from a USB drive using VMWare Player. I realize it could hit performance problems but that's what I want to do. I really don't understand why this is a problem with VMWare Workstation.
2018/08/16
[ "https://superuser.com/questions/1354385", "https://superuser.com", "https://superuser.com/users/314943/" ]
This is because the downloaded VM is contained in an OVF file and needs to be imported. <https://pubs.vmware.com/workstation-9/index.jsp?topic=%2Fcom.vmware.ws.using.doc%2FGUID-DDCBE9C0-0EC9-4D09-8042-18436DA62F7A.html> Alternately, because an OVF file is just a compressed file containing all of the VM elements (configuration files, virtual hard disk, etc.) you can simply uncompress the OVF file with a tool like 7-Zip and then open it directly in VMware Workstation.
31,768,830
I am doing a recursive walk through directories to make changes to files. My change file function needs the full path of the file to be able to do stuff. However, what my program is doing right now is just getting the name of the current file or folder but not the full path. My approach is that I would make a string and keeps appending names to it until I get the full path. However, because I'm doing recursion, I'm having troubles passing the string around to append more strings to it. This is my code: ``` #include <stdio.h> #include <stdlib.h> #include <regex.h> #include <string.h> #include <dirent.h> #include <unistd.h> #include <sys/types.h> #include <errno.h> void recursiveWalk(const char *pathName, char *fullPath, int level) { DIR *dir; struct dirent *entry; if (!(dir = opendir(pathName))) { fprintf(stderr, "Could not open directory\n"); return; } if (!(entry = readdir(dir))) { fprintf(stderr, "Could not read directory\n"); return; } do { if (entry->d_type == DT_DIR) { // found subdirectory char path[1024]; int len = snprintf(path, sizeof(path)-1, "%s/%s", pathName, entry->d_name); // get depth path[len] = 0; // skip hidden paths if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } fprintf(stdout, "%*s[%s]\n", level*2, "", entry->d_name); // Append fullPath to entry->d_name here recursiveWalk(path, fullPath, level + 1); } else { // files fprintf(stdout, "%*s- %s\n", level*2, "", entry->d_name); //changeFile(fullPath); } } while (entry = readdir(dir)); closedir(dir); } int main(int argn, char *argv[]) { int level = 0; recursiveWalk(".", "", level); return 0; } ```
2015/08/02
[ "https://Stackoverflow.com/questions/31768830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4807625/" ]
Well there are a number of little problems in your code. * you never use nor change `fullPath` in `recursiveWalk` * your formats are *weird* : you use `level*2` to limit the number of characters printed from an empty string * you compute the actual path only when you have found a directory, while you say you need it to change a file. * you add `path[len] = 0` after a `snprintf` when `snprintf` guarantees that but buffer is null terminated But apart from that, you correctly pass the path to the analyzed dir append to the path passed in initial call, but in `pathName` variable, and computed as `path`. So a possible fix for your code would be : * fix the formats for printf * remove the unused `fullPath` parameter from `recursiveWalk` * allways compute `path` and use it in the *file* branch * comment out the unnecessary `path[len] = '\0'` * I also replaced `while (entry = readdir(dir));` with `while ((entry = readdir(dir)));` to explicitely tell the compiler that I want to set entry and then test its value - and remove the warning Possible code: ``` #include <stdio.h> #include <stdlib.h> #include <regex.h> #include <string.h> #include <dirent.h> #include <unistd.h> #include <sys/types.h> #include <errno.h> void recursiveWalk(const char *pathName, int level) { DIR *dir; struct dirent *entry; if (!(dir = opendir(pathName))) { fprintf(stderr, "Could not open directory\n"); return; } if (!(entry = readdir(dir))) { fprintf(stderr, "Could not read directory\n"); return; } do { char path[1024]; int len = snprintf(path, sizeof(path)-1, "%s/%s", pathName, entry->d_name); // get depth // path[len] = 0; if (entry->d_type == DT_DIR) { // found subdirectory // skip hidden paths if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { continue; } fprintf(stdout, "%s [%s] (%d)\n", pathName, entry->d_name, level); // Append fullPath to entry->d_name here recursiveWalk(path, level + 1); } else { // files fprintf(stdout, "%s (%d)\n", path, level); //changeFile(fullPath); } } while ((entry = readdir(dir))); closedir(dir); } int main(int argn, char *argv[]) { int level = 0; recursiveWalk(".", level); return 0; } ```
3,823,963
The same question is asked [here.](https://stackoverflow.com/questions/1675893/jquery-close-dialog-on-click-anywhere) but it doesn't state the source, and the solution given is not directly applicable in my case afaik. I might get modded down for this, but I am asking anyway. **My Entire Code:** ``` <html><head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/jquery-ui.min.js"></script> <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/humanity/jquery-ui.css" type="text/css" /> </head> <body><div id="dialog" title="Title Box"> <p>Stuff here</p> </div> <script type="text/javascript"> jQuery(document).ready(function() { jQuery("#dialog").dialog({ bgiframe: true, autoOpen: false, height: 100, modal: true }); }); </script> <a href="#" onclick="jQuery('#dialog').dialog('open'); return false">Click to view</a> </body></html> ``` All script files are third party hosted, and I would want to keep it that way. ***How do I get "click anywhere (outside the box)to close the modal box" functionality?***
2010/09/29
[ "https://Stackoverflow.com/questions/3823963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/405861/" ]
``` <html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js"></script> <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/themes/humanity/jquery-ui.css" type="text/css" /> </head> <body> <div id="dialog" title="Title Box"> <p>Stuff here</p> </div> <script type="text/javascript"> jQuery( function() { jQuery("#dialog") .dialog( { bgiframe: true, autoOpen: false, height: 100, modal: true } ); jQuery('body') .bind( 'click', function(e){ if( jQuery('#dialog').dialog('isOpen') && !jQuery(e.target).is('.ui-dialog, a') && !jQuery(e.target).closest('.ui-dialog').length ){ jQuery('#dialog').dialog('close'); } } ); } ); </script> <a href="#" onclick="jQuery('#dialog').dialog('open'); return false">Click to view</a> </body> </html> ```
28,034,653
I want to stack several images using imagemagick. The result I want is the same as I get when I import all images as layers into Gimp and set the layer transparency to some value. Each image is transparent with a circle in the center of various sizes. Overlaying all N images with a 100/N% opacity should give me something like a blurry blob with radially increasing transparency. Here are three example images. ![](https://i.stack.imgur.com/MvSLW.png) ![](https://i.stack.imgur.com/7ZLEg.png) ![](https://i.stack.imgur.com/HL6CG.png) However if I try to do this with imagemagick, I get a black background: ``` convert image50.png -background transparent -alpha set -channel A -fx "0.2" \( image60.png -background transparent -alpha set -channel A -fx "0.2" \) -compose overlay -composite -flatten result.png ``` Edit: After Mark Setchells latest comments, I got ![](https://i.stack.imgur.com/0zzoO.png) What I want is that those areas that appear in all images (the center in the example) add up to to non-transparent region, while those regions that appear only on fewer images get more and more transparent. Marks example seems to work for 3 images, but not for a larger stack. The result I would like to get would be this one (here I emphasize the transparent regions by adding a non-white background): ![](https://i.stack.imgur.com/Mx3VA.png) The example images are made from this one ![](https://i.stack.imgur.com/hjWgF.png) using this bash command: ``` for i in $(seq 10 10 90); do f="image$i.png" convert http://i.stack.imgur.com/hjWgF.png -quality 100 -fuzz $i% -fill white -transparent black $f done ```
2015/01/19
[ "https://Stackoverflow.com/questions/28034653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2108771/" ]
``` #!/bin/bash # Calculate how many images we have N=$(ls image*.png|wc -l) echo N:$N # Generate mask, start with black and add in components from each subsequent image i=0 convert image10.png -evaluate set 0 mask.png for f in image*png;do convert mask.png \( "$f" -alpha extract -evaluate divide $N \) -compose plus -composite mask.png done # Generate output image convert image*.png \ -compose overlay -composite \ mask.png -compose copy-opacity -composite out.png ```
36,500,784
Apologies if there is another feed with this same problem, I have tried different suggested solutions but I still get an error, and I cant see why! I want to update a row in my table using a html form. I have populated the form with the existing values, and want to be able to edit those and update them when the form is submitted, but I am getting this error: > > Fatal error: Uncaught exception 'PDOException' with message > 'SQLSTATE[HY093]: Invalid parameter number: parameter was not defined' > in > /Applications/XAMPP/xamppfiles/htdocs/love-deals/admin/update\_offer.php:46 > Stack trace: #0 > /Applications/XAMPP/xamppfiles/htdocs/love-deals/admin/update\_offer.php(46): > PDOStatement->execute(Array) #1 {main} thrown in > /Applications/XAMPP/xamppfiles/htdocs/love-deals/admin/update\_offer.php > on line 46 > > > Here is the php / sql code: ``` if(isset($_POST['update'])) { $updateTitle = trim($_POST['title']); $updateDesc = trim($_POST['desc']); $updateRedeem = trim($_POST['redeem']); $updateStart = trim($_POST['start']); $updateExpiry = trim($_POST['expiry']); $updateCode = trim($_POST['code']); $updateTerms = trim($_POST['terms']); $updateImage = trim($_POST['image']); $updateUrl = trim($_POST['url']); $updateSql = 'UPDATE codes SET (title,description,redemption,start,expiry,textcode,terms,image,url) = (:title,:description,:redeem,:start,:exp,:code,:terms,:image,:url) WHERE id=:offerid'; $update = $db->prepare($updateSql); $update->execute(array(':title'=>$updateTitle,':description'=>$updateDesc,':redeem'=>$updateRedeem,':start'=>$updateStart,':exp'=>$updateExpiry,':code'=>$updateCode,':terms'=>$updateTerms,':image'=>$updateImage,':url'=>$updateUrl,':id'=>$offerID)); } ``` and the html form: ``` <form id="update_offer" class="col-md-6 col-md-offset-3" method="post" action="update_offer.php?id=<?php echo $offerID; ?>"> <div class="form-group col-md-12"> <label class="col-md-12" for="title">Title</label> <input id="title" class="form-control col-md-12" type="text" name="title" placeholder="Offer Title" value="<?php echo $title; ?>" required> </div> <div class="form-group col-md-12"> <label class="col-md-12" for="desc">Description</label> <textarea id="desc" class="form-control col-md-12" name="desc" placeholder="Description" value="<?php echo $desc; ?>"></textarea> </div> <div class="form-group col-md-12"> <label class="col-md-12" for="redeem">Redemption</label> <input id="redeem" class="form-control col-md-12" type="text" name="redeem" placeholder="Where to redeem" value="<?php echo $redeem; ?>" required> </div> <div class="form-group col-md-12"> <label class="col-md-12" for="start">Start Date</label> <input id="start" class="form-control col-md-12" type="date" name="start" value="<?php echo $startDate->format('Y-m-d'); ?>" min="<?php echo date('Y-m-d') ?>" max="2021-12-31" required> </div> <div class="form-group col-md-12"> <label class="col-md-12" for="expiry">Expiry Date</label> <input id="expiry" class="form-control col-md-12" type="date" name="expiry" value="<?php echo $expDate->format('Y-m-d'); ?>" min="<?php echo date('Y-m-d') ?>" max="2021-12-31" required> </div> <div class="form-group col-md-12"> <label class="col-md-12" for="code">Code</label> <input id="code" class="form-control col-md-12" type="text" name="code" placeholder="Code (if applicable)" value="<?php echo $code; ?>"> </div> <div class="form-group col-md-12"> <label class="col-md-12" for="terms">Terms</label> <textarea id="terms" class="form-control col-md-12" name="terms" placeholder="Terms & Conditions" value="<?php echo $terms; ?>" required></textarea> </div> <div class="form-group col-md-12"> <label class="col-md-12" for="url">Offer URL</label> <input id="url" class="form-control col-md-12" type="text" name="url" placeholder="Offer URL (if applicable)" value="<?php echo $url; ?>"> </div> <div class="form-group col-md-12"> <label class="col-md-8" for="image">Image <img src="../images/offers/<?php echo $image; ?>" alt="" style="width: 200px;" /></label> <input id="image" class="form-control col-md-4" type="file" name="image"> </div> <div class="form-group col-md-12 pull-right"> <button id="update" type="submit" name="update" class="btn btn-primary"><i class="glyphicon glyphicon-refresh"></i> Update</button> </div> </form> ``` what am i doing wrong?! Im still learning php etc, so please be gentle, any help is much appreciated.
2016/04/08
[ "https://Stackoverflow.com/questions/36500784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5968121/" ]
First, you have wrong syntax for update statement, as other guys mentioned already, change: ``` UPDATE codes SET (title,description,redemption,start,expiry,textcode,terms,image,url) = (:title,:description,:redeem,:start,:exp,:code,:terms,:image,:url) WHERE id=:offerid ``` **Into** ``` UPDATE `codes` SET `title` = :title, `description` = :description, `redemption` = :redeem, `start` = :start `expiry` = :expiry `textcode` = :code `terms` = :terms `image` = :image `url` = :url WHERE `id` = :offerid ``` Learn more about the SQL Update syntax [here](http://dev.mysql.com/doc/refman/5.7/en/update.html). Then, one thing more you have a mistake in `execute()`. Change your `:id` into `:offerid` like below: ``` $update->execute(array( ':title' => $updateTitle, ':description' => $updateDesc, ':redeem' => $updateRedeem, ':start' => $updateStart, ':exp' => $updateExpiry, ':code' => $updateCode, ':terms' => $updateTerms, ':image' => $updateImage, ':url' => $updateUrl, ':offerid' => $offerID )); ```
70,966,975
``` string = "C:\\folder\\important\\week1.xlsx" ``` I need to extract the file name alone, "week1.xlsx" from this string. But for some reason, it doesn't work.
2022/02/03
[ "https://Stackoverflow.com/questions/70966975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15044904/" ]
You can use `basename`: ``` import os str(os.path.basename("C:\\folder\\important\\week1.xlsx")) => 'week1.xlsx' ```
16,643
Which questions are most successful at gauging the UX design experience in a candidate? What approaches are best used during a job interview for a UX design position?
2012/01/27
[ "https://ux.stackexchange.com/questions/16643", "https://ux.stackexchange.com", "https://ux.stackexchange.com/users/5113/" ]
**First:** Hello. Welcome. Thank you for coming to see us today. Take a seat. Coffee. Put interviewee at ease. **Then:** *"Tell me about the experience you had getting here today."* It has no correct answer since the interviewer knows nothing about the journey. But the interviewee actually undertook the complete experience so should be very much in a comfort zone. It's great for seeing what was noticed, how it is communicated to someone who wasn't there, and of course it's very much a case of seeing if they pick up on what you are expecting of them and can convey the experience descriptively and passionately ( or not...) and if they can actually 'tell a story' in the process. It's such a lovely little big question.
27,593,856
`pair` looks like this: ``` std::vector<std::pair<uint64 /*id*/, std::string /*message*/> ``` And if I want 3 variables in `vector`? Can I use pair or what?
2014/12/21
[ "https://Stackoverflow.com/questions/27593856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3925125/" ]
If I have understood correctly you could use `std::tuple` declared in header `<tuple>`. For example ``` std::vector<std::tuple<uint64, std::string, SomeOtherType>> v; ```
12,192,616
What are the ciphers supported by JSSE in Apache Tomcat server? How can i enable AES256 and reorder the ciphers?
2012/08/30
[ "https://Stackoverflow.com/questions/12192616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/584095/" ]
If you aren't using the APR native connector, Tomcat supports whatever Java supports, which does include AES256, possibly requiring the unlimited-strength crypto JARs. If you are using native APR, Tomcat supports whatever its OpenSSL supports, which you can determine, somehow, via the OpenSSL.exe command. The enabled cipher suites should be configurable in the Connector element of server.xml.
906,752
Given any meromorphic function, can it be represented as $$c\prod\_i (z-z\_i)^{n\_i} $$ where $ n\_i\in\mathbb Z$ and $n\_i> 0$ denotes the multiplicity of the zero $ z\_i $ and $ n\_i <0$ for the poles?
2014/08/23
[ "https://math.stackexchange.com/questions/906752", "https://math.stackexchange.com", "https://math.stackexchange.com/users/163/" ]
Short answer: Not all, but... Turns out this is more complicated than [user170431's answer](https://math.stackexchange.com/a/906760/163) suggested, though it hinted at the correct direction. Given a meromorphic function $f(z)$ with poles at $\{p\_i\}$ of multiplicites $\{n\_{p\_i}\}$, one can indeed use [Mittag-Leffler's theorem](http://en.wikipedia.org/wiki/Mittag-Leffler%27s_theorem) to obtain a holomorphic function $$h(z) = f(z) - \sum\_i \pi\_{p\_i}(1/(z-p\_i))$$ where $\pi\_{p\_i}$ denotes a polynomial of degree $n\_{p\_i}$, and due to their finite order (meromorphic functions don't have essential singularities) one can expand $f(z)$ to the common denominator. What the other answer and my question's assumption did however neglect was the full extend of the [Weierstrass factorization theorem](http://en.wikipedia.org/wiki/Weierstrass_factorization_theorem), according to which $h(z)$ actually factorizes into $$h(z) = e^{g(z)}\prod\_j(z-z\_j)^{n\_{z\_j}}$$ where $n\_{z\_j}$ denotes the multiplicity of the zero $z\_j$ and $g(z)$ is an entire function. Note that I simplified matters here, for infinitely many zeros (or of infinite multiplicity) parts of the exponential are inside the product as "elementary factors" in order to have the infinite product converge. In my sloppy notation, they are part of $\exp g(z)$ though. Therefore, the actual representation of a meromorphic function is $$f(z) = e^{g(z)}\prod\_i(z-z\_i)^{n\_i}$$ (now the $z\_i$ also include the poles again, as in the question's notation). Only if there are finitely many zeros of finite multiplicities (i.e. a quotient of two polynomials), the representation without an exponential in front (i.e. a constant $g(z)$) is valid.
23,246,560
I noticed that one of my submission pages with ReCaptcha is pulling this file: ``` http://www.google.com/js/th/tCBzJRqneV5tJFCAUdKmLPYTyVH8SN5m5IZzuhnsVzY.js ``` Of course, being hosted at Google, I want to assume this must be fine. Although the file contents start with this: ``` /* Anti-spam. Questions? Write to (rot13) guvagvary-dhrfgvbaf@tbbtyr.pbz */ ``` ...followed by a very long `eval()` statement. This is the beginning of it (edit: this is now the entire code block): ``` (function(){eval('var f=function(a,b,c){if(b=typeof a,"object"==b)if(a){if(a instanceof Array)return"array";if(a instanceof Object)return b;if(c=Object.prototype.toString.call(a),"[object Window]"==c)return"object";if("[object Array]"==c||"number"==typeof a.length&&"undefined"!=typeof a.splice&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("splice"))return"array";if("[object Function]"==c||"undefined"!=typeof a.call&&"undefined"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("call"))return"function"}else return"null";else if("function"==b&&"undefined"==typeof a.call)return"object";return b},n=function(a,b,c,d,e){c=a.split("."),d=g,c[0]in d||!d.execScript||d.execScript("var "+c[0]);for(;c.length&&(e=c.shift());)c.length||b===k?d=d[e]?d[e]:d[e]={}:d[e]=b},p=Date.now||function(){return+new Date},r=/&/g,t=/</g,u=/>/g,w=/"/g,x=/\'/g,k=void 0,g=this,z,A="".oa?"".ma():"",E=(/[&<>"\']/.test(A)&&(-1!=A.indexOf("&")&&(A=A.replace(r,"&amp;")),-1!=A.indexOf("<")&&(A=A.replace(t,"&lt;")),-1!=A.indexOf(">")&&(A=A.replace(u,"&gt;")),-1!=A.indexOf(\'"\')&&(A=A.replace(w,"&quot;")),-1!=A.indexOf("\'")&&(A=A.replace(x,"&#39;"))),new function(){p()},function(a,b,c,d,e,h){try{if(this.j=2048,this.c=[],B(this,this.b,0),B(this,this.l,0),B(this,this.p,0),B(this,this.h,[]),B(this,this.d,[]),B(this,this.H,"object"==typeof window?window:g),B(this,this.I,this),B(this,this.r,0),B(this,this.F,0),B(this,this.G,0),B(this,this.f,C(4)),B(this,this.o,[]),B(this,this.k,{}),this.q=true,a&&","==a[0])this.m=a;else{if(window.atob){for(c=window.atob(a),a=[],e=d=0;e<c.length;e++){for(h=c.charCodeAt(e);255<h;)a[d++]=h&255,h>>=8;a[d++]=h}b=a}else b=null;(this.e=b)&&this.e.length?(this.K=[],this.s()):this.g(this.U)}}catch(l){D(this,l)}}),G=(E.prototype.g=function(a,b,c,d){d=this.a(this.l),a=[a,d>>8&255,d&255],c!=k&&a.push(c),0==this.a(this.h).length&&(this.c[this.h]=k,B(this,this.h,a)),c="",b&&(b.message&&(c+=b.message),b.stack&&(c+=":"+b.stack)),3<this.j&&(c=c.slice(0,this.j-3),this.j-=c.length+3,c=F(c),G(this,this.f,H(c.length,2).concat(c),this.$))},function(a,b,c,d,e,h){for(e=a.a(b),b=b==a.f?function(b,c,d,h){if(c=e.length,d=c-4>>3,e.ba!=d){e.ba=d,d=(d<<3)-4,h=[0,0,0,a.a(a.G)];try{e.aa=I(J(e,d),J(e,d+4),h)}catch(s){throw s;}}e.push(e.aa[c&7]^b)}:function(a){e.push(a)},d&&b(d&255),d=c.length,h=0;h<d;h++)b(c[h])}),K=function(a,b,c,d,e,h,l,q,m){return c=function(a,s,v){for(a=d[e.D],s=a===b,a=a&&a[e.D],v=0;a&&a!=h&&a!=l&&a!=q&&a!=m&&20>v;)v++,a=a[e.D];return c[e.ga+s+!(!a+(v>>2))]},d=function(){return c()},e=E.prototype,h=e.s,l=e.Q,m=e.g,q=E,d[e.J]=e,c[e.fa]=a,a=k,d},L=function(a,b,c){if(b=a.a(a.b),!(b in a.e))throw a.g(a.Y),a.u;return a.t==k&&(a.t=J(a.e,b-4),a.B=k),a.B!=b>>3&&(a.B=b>>3,c=[0,0,0,a.a(a.p)],a.Z=I(a.t,a.B,c)),B(a,a.b,b+1),a.e[b]^a.Z[b%8]},F=function(a,b,c,d,e){for(a=a.replace(/\\r\\n/g,"\\n"),b=[],d=c=0;d<a.length;d++)e=a.charCodeAt(d),128>e?b[c++]=e:(2048>e?b[c++]=e>>6|192:(b[c++]=e>>12|224,b[c++]=e>>6&63|128),b[c++]=e&63|128);return b},B=function(a,b,c){if(b==a.b||b==a.l)a.c[b]?a.c[b].V(c):a.c[b]=M(c);else if(b!=a.d&&b!=a.f&&b!=a.h||!a.c[b])a.c[b]=K(c,a.a);b==a.p&&(a.t=k,B(a,a.b,a.a(a.b)+4))},I=function(a,b,c,d){try{for(d=0;76138654016!=d;)a+=(b<<4^b>>>5)+b^d+c[d&3],d+=2379332938,b+=(a<<4^a>>>5)+a^d+c[d>>>11&3];return[a>>>24,a>>16&255,a>>8&255,a&255,b>>>24,b>>16&255,b>>8&255,b&255]}catch(e){throw e;}},N=function(a,b){return b<=a.ca?b==a.h||b==a.d||b==a.f||b==a.o?a.n:b==a.P||b==a.H||b==a.I||b==a.k?a.v:b==a.w?a.i:4:[1,2,4,a.n,a.v,a.i][b%a.da]},O=(E.prototype.la=function(a,b){b.push(a[0]<<24|a[1]<<16|a[2]<<8|a[3]),b.push(a[4]<<24|a[5]<<16|a[6]<<8|a[7]),b.push(a[8]<<24|a[9]<<16|a[10]<<8|a[11])},function(a,b,c,d){for(b={},b.N=a.a(L(a)),b.O=L(a),c=L(a)-1,d=L(a),b.self=a.a(d),b.C=[];c--;)d=L(a),b.C.push(a.a(d));return b}),Q=(E.prototype.ja=function(a,b,c,d){if(3==a.length){for(c=0;3>c;c++)b[c]+=a[c];for(d=[13,8,13,12,16,5,3,10,15],c=0;9>c;c++)b[3](b,c%3,d[c])}},function(a,b,c,d){return c=a.a(a.b),a.e&&c<a.e.length?(B(a,a.b,a.e.length),P(a,b)):B(a,a.b,b),d=a.s(),B(a,a.b,c),d}),H=(E.prototype.ka=function(a,b,c,d){d=a[(b+2)%3],a[b]=a[b]-a[(b+1)%3]-d^(1==b?d<<c:d>>>c)},function(a,b,c,d){for(d=b-1,c=[];0<=d;d--)c[b-1-d]=a>>8*d&255;return c}),M=function(a,b,c){return b=function(){return c()},b.V=function(b){a=b},c=function(){return a},b},R=function(a,b,c,d){return function(){if(!d||a.q)return B(a,a.P,arguments),B(a,a.k,c),Q(a,b)}},P=(E.prototype.a=function(a,b){if(b=this.c[a],b===k)throw this.g(this.ea,0,a),this.u;return b()},function(a,b){a.K.push(a.c.slice()),a.c[a.b]=k,B(a,a.b,b)}),J=function(a,b){return a[b]<<24|a[b+1]<<16|a[b+2]<<8|a[b+3]},C=function(a,b){for(b=Array(a);a--;)b[a]=255*Math.random()|0;return b},D=function(a,b){a.m=("E:"+b.message+":"+b.stack).slice(0,2048)};z=E.prototype,z.M=[function(){},function(a,b,c,d,e){b=L(a),c=L(a),d=a.a(b),b=N(a,b),e=N(a,c),e==a.i||e==a.n?d=""+d:0<b&&(1==b?d&=255:2==b?d&=65535:4==b&&(d&=4294967295)),B(a,c,d)},function(a,b,c,d,e,h,l,q,m){if(b=L(a),c=N(a,b),0<c){for(d=0;c--;)d=d<<8|L(a);B(a,b,d)}else if(c!=a.v){if(d=L(a)<<8|L(a),c==a.i)if(c="",a.c[a.w]!=k)for(e=a.a(a.w);d--;)h=e[L(a)<<8|L(a)],c+=h;else{for(c=Array(d),e=0;e<d;e++)c[e]=L(a);for(d=c,c=[],h=e=0;e<d.length;)l=d[e++],128>l?c[h++]=String.fromCharCode(l):191<l&&224>l?(q=d[e++],c[h++]=String.fromCharCode((l&31)<<6|q&63)):(q=d[e++],m=d[e++],c[h++]=String.fromCharCode((l&15)<<12|(q&63)<<6|m&63));c=c.join("")}else for(c=Array(d),e=0;e<d;e++)c[e]=L(a);B(a,b,c)}},function(a){L(a)},function(a,b,c,d){b=L(a),c=L(a),d=L(a),c=a.a(c),b=a.a(b),B(a,d,b[c])},function(a,b,c){b=L(a),c=L(a),b=a.a(b),B(a,c,f(b))},function(a,b,c,d,e){b=L(a),c=L(a),d=N(a,b),e=N(a,c),c!=a.h&&(d==a.i&&e==a.i?(a.c[c]==k&&B(a,c,""),B(a,c,a.a(c)+a.a(b))):e==a.n&&(0>d?(b=a.a(b),d==a.i&&(b=F(""+b)),c!=a.d&&c!=a.f&&c!=a.o||G(a,c,H(b.length,2)),G(a,c,b)):0<d&&G(a,c,H(a.a(b),d))))},function(a,b,c){b=L(a),c=L(a),B(a,c,function(a){return eval(a)}(a.a(b)))},function(a,b,c){b=L(a),c=L(a),B(a,c,a.a(c)-a.a(b))},function(a,b){b=O(a),B(a,b.O,b.N.apply(b.self,b.C))},function(a,b,c){b=L(a),c=L(a),B(a,c,a.a(c)%a.a(b))},function(a,b,c,d,e){b=L(a),c=a.a(L(a)),d=a.a(L(a)),e=a.a(L(a)),a.a(b).addEventListener(c,R(a,d,e,true),false)},function(a,b,c,d){b=L(a),c=L(a),d=L(a),a.a(b)[a.a(c)]=a.a(d)},function(){},function(a,b,c){b=L(a),c=L(a),B(a,c,a.a(c)+a.a(b))},function(a,b,c){b=L(a),c=L(a),0!=a.a(b)&&B(a,a.b,a.a(c))},function(a,b,c,d){b=L(a),c=L(a),d=L(a),a.a(b)==a.a(c)&&B(a,d,a.a(d)+1)},function(a,b,c,d){b=L(a),c=L(a),d=L(a),a.a(b)>a.a(c)&&B(a,d,a.a(d)+1)},function(a,b,c,d){b=L(a),c=L(a),d=L(a),B(a,d,a.a(b)<<c)},function(a,b,c,d){b=L(a),c=L(a),d=L(a),B(a,d,a.a(b)|a.a(c))},function(a,b){b=a.a(L(a)),P(a,b)},function(a,b,c,d){if(b=a.K.pop()){for(c=L(a);0<c;c--)d=L(a),b[d]=a.c[d];a.c=b}else B(a,a.b,a.e.length)},function(a,b,c,d){b=L(a),c=L(a),d=L(a),B(a,d,(a.a(b)in a.a(c))+0)},function(a,b,c,d){b=L(a),c=a.a(L(a)),d=a.a(L(a)),B(a,b,R(a,c,d))},function(a,b,c){b=L(a),c=L(a),B(a,c,a.a(c)*a.a(b))},function(a,b,c,d){b=L(a),c=L(a),d=L(a),B(a,d,a.a(b)>>c)},function(a,b,c,d){b=L(a),c=L(a),d=L(a),B(a,d,a.a(b)||a.a(c))},function(a,b,c,d,e){b=O(a),c=b.C,d=b.self,e=b.N;switch(c.length){case 0:c=new d[e];break;case 1:c=new d[e](c[0]);break;case 2:c=new d[e](c[0],c[1]);break;case 3:c=new d[e](c[0],c[1],c[2]);break;case 4:c=new d[e](c[0],c[1],c[2],c[3]);break;default:a.g(a.A);return}B(a,b.O,c)},function(a,b,c,d,e,h){if(b=L(a),c=L(a),d=L(a),e=L(a),b=a.a(b),c=a.a(c),d=a.a(d),a=a.a(e),"object"==f(b)){for(h in e=[],b)e.push(h);b=e}for(h=b.length,e=0;e<h;e+=d)c(b.slice(e,e+d),a)}],z.b=0,z.p=1,z.h=2,z.l=3,z.d=4,z.w=5,z.P=6,z.L=8,z.H=9,z.I=10,z.r=11,z.F=12,z.G=13,z.f=14,z.o=15,z.k=16,z.ca=17,z.R=253,z.$=254,z.S=248,z.T=216,z.da=6,z.i=-1,z.n=-2,z.v=-3,z.U=17,z.W=21,z.A=22,z.ea=30,z.Y=31,z.X=33,z.u={},z.D="caller",z.J="toString",z.ga=34,z.fa=36,E.prototype.ia=function(a){return(a=window.performance)&&a.now?function(){return a.now()|0}:function(){return+new Date}}(),E.prototype.Q=function(a,b,c,d,e,h,l,q,m,y,s){if(this.m)return this.m;try{if(this.q=false,b=this.a(this.d).length,c=this.a(this.f).length,d=this.j,this.c[this.L]&&Q(this,this.a(this.L)),e=this.a(this.h),0<e.length&&G(this,this.d,H(e.length,2).concat(e),this.R),h=this.a(this.F)&255,h-=this.a(this.d).length+4,l=this.a(this.f),4<l.length&&(h-=l.length+3),0<h&&G(this,this.d,H(h,2).concat(C(h)),this.S),4<l.length&&G(this,this.d,H(l.length,2).concat(l),this.T),q=[241].concat(this.a(this.d)),window.btoa?(y=window.btoa(String.fromCharCode.apply(null,q)),m=y=y.replace(/\\+/g,"-").replace(/\\//g,"_").replace(/=/g,"")):m=k,m)m=","+m;else for(m="",e=0;e<q.length;e++)s=q[e][this.J](16),1==s.length&&(s="0"+s),m+=s;this.a(this.d).length=b,this.a(this.f).length=c,this.j=d,this.q=true,a=m}catch(v){D(this,v),a=this.m}return a},E.prototype.s=function(a,b,c,d,e,h){try{for(a=this.e.length,b=2001,c=k,d=0;--b&&(d=this.a(this.b))<a;)try{B(this,this.l,d),e=L(this)%this.M.length,(c=this.M[e])?c(this):this.g(this.W,0,e)}catch(l){l!=this.u&&((h=this.a(this.r))?(B(this,h,l),B(this,this.r,0)):this.g(this.A,l))}b||this.g(this.X)}catch(q){try{this.g(this.A,q)}catch(m){D(this,m)}}return this.a(this.k)},E.prototype.ha=function(a,b){return b=this.Q(),a&&a(b),b};try{window.addEventListener("unload",function(){},false)}catch(S){}n("thintinel.th",E),n("thintinel.th.prototype.exec",E.prototype.ha);')})() ``` I spent an hour trying to deobfuscate this, but gave up. I then tried Googling for information about this, via words from the first comment line above, and the URL of the .js file, but nothing too relevant came up. Then I tried other sites that use ReCaptcha and checked if they were pulling something similar. Finding sites that use ReCaptcha isn't as easy as I thought (I'm sure there are many, it's just not an easy search). The few I found did pull a similarly-named file from the google.com/js/th path, but they tended to have far less code in it than mine. If this is a legitimate part of ReCaptcha, it seems they could do a much better job of not making it look suspicious. There's no indication of what the hell it is or that it even has anything to do with ReCaptcha. Right now I'm not too worried, as I'm assuming it IS legitimate. I mainly wanted to get this up someplace for others who may have noticed it and gotten worried. If there are no answers I might just answer it myself with a "yeah it's probably fine".
2014/04/23
[ "https://Stackoverflow.com/questions/23246560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2066896/" ]
It creates an object called `thintinel`, in the global scope, and this object is referenced directly by `/recaptcha/api/js/recaptha_ajax.js`. It's almost certainly legitimate and my best guess is that it checks for a traditional, interactive browser rather than a thin bot-controlled client.
1,639,706
On my linux (ubuntu 20.04) workstation i usually have a virtualbox VM with windows 10 running, to get access to some work-related things. If I accidentally leave the virtualbox window focused it prevents the screen saver from locking the screen. Is there a setting, either in ubuntu or in virtualbox, that allows the screen saver to lock the screen when the virtualbox windows is focused?
2021/04/06
[ "https://superuser.com/questions/1639706", "https://superuser.com", "https://superuser.com/users/1294422/" ]
Assuming a different Windows license (old Windows license, new machine with new Windows License), there is not any issue. Still, for clarity for you and for the longer term, install, get your data in a reasonable time and then remove the drive or format it. The reason is (a) the old license may not run properly on the new machine and (b) if it was OEM, the license is not portable anyway. You should not have any issue.
694
I'm running Lightroom 2.6 on Windows XP and it runs painfully slow. Just navigating from one image to the next takes a few seconds. What can I do to speed it up?
2010/07/16
[ "https://photo.stackexchange.com/questions/694", "https://photo.stackexchange.com", "https://photo.stackexchange.com/users/190/" ]
Something that hasn't been mentioned yet: in 'Catalog Settings' turn off 'Automatically write changes into XMP'. This will prevent LR from automatically dumping its catalog metadata, keywords, rating, labels and develop settings back to your photo files. By doing so you will reduce the number of disk operations performed by LR. You can still write your metadata back manually, as [I describe in this other question](https://photo.stackexchange.com/questions/2680/lightroom-data-storage/2953#2953). I have 8GB of RAM and I process 21MP RAW files out of a Canon 5DMII. Increasing disk performance is how I made it run faster. I replaced a pair of fairly zippy Hitachi SATA 15,000 RPM drives by a pair of 160GB Intel X25G2 SSD. Be careful with your choice of SSD drives, they are not born equal. Most of them read really fast, but many are slow on write. Pair your SSD with a modern operating system like Windows 7, one that supports the [TRIM](http://en.wikipedia.org/wiki/TRIM) command. What should you put on a SSD and what should you leave on a standard drive? Opinions differ, but here is what I would recommend: * your LR catalog file (Lightroom 3 Catalog.lrcat), which is where LR stores its metadata, keywords, rating, labels and develop settings * your Previews directory (Lightroom 3 Catalog Previews.lrdata), which is where LR stores intermediate representation of your photos for faster viewing (1:1, low res, thumbnails, etc) * your Adobe Camera RAW Cache (ACR Cache) * your RAW files, or at least a subset of them What is the Camera RAW Cache? Quoting Jeff Schewe via Luminous Landscape Forum > > Every time you open an image in Camera > Raw the full resolution of the image > must be loaded into Camera Raw… as you > can imagine, this can be pretty > processor intensive… the Camera Raw > cache will cache recently opened > images to make re-opening them faster. > There’s a preference limit to > determine the size and the cache will > remain constant in size by flushing > out older cache files when newer > images are loaded into Camera Raw. > > > You can change the default location of your catalog, previews and Camera RAW Cache from the Preferences and group them on the same SSD. I would definitely recommend increasing the size of your ACR Cache, if you can afford it. RAW files are big. You don't need to have all of them on a SSD, but what about the past 6 months worth of photos? Move older photos back to a standard drive every month or so (do it from LR of course). Do you need to put LR or the whole Operating System on a SSD? If you can, sure, it will start faster and feel a bit more responsive, but I don't think it's critical. If you don't have a lot of RAM though, try to put your page file and TEMP directories on the SSD. Should you go RAID0? I really recommend against it, unless you have really strong backup habits and monitor your RAID controller regularly. Remember, RAID0 uses 2 drives: if one dies, you lose the data on both. Don't risk it. I personally like RAID1 a lot for this very reason and from past experience. Finally, you will "feel" LR run faster if you let it generate your 1:1 photo previews during import. I usually do something else during import anyway, run some errands or whatnot. In any case LR has to generate your 1:1 previews sooner or later when you go to the Develop module, right? So you might as well let this happen during import.
32,187,934
I am trying to make a Python script which counts the amount of letters in a randomly chosen word for my Hangman game. I already looked around on the web, but most thing I could find was count specific letters in a word. After more looking around I ended up with this, which does not work for some reason. If someone could point out the errors, that'd be greatly appreciated. ``` wordList = ["Tree", "Fish", "Monkey"] wordChosen = random.choice(wordList) wordCounter = wordChosen.lower().count['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] print(wordCounter) ```
2015/08/24
[ "https://Stackoverflow.com/questions/32187934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5246668/" ]
Are you looking for `collections.Counter`? ``` >>> import collections >>> print(collections.Counter("Monkey")) Counter({'M': 1, 'y': 1, 'k': 1, 'o': 1, 'n': 1, 'e': 1}) >>> print(collections.Counter("Tree")) Counter({'e': 2, 'T': 1, 'r': 1}) >>> c = collections.Counter("Tree") >>> print("The word 'Tree' has {} distinct letters".format(len(c))) The word 'Tree' has 3 distinct letters >>> print("The word 'Tree' has {} instances of the letter 'e'".format(c['e'])) The word 'Tree' has 2 instances of the letter 'e' ```
33,264,005
This Nuspec reference explains the description and summary text fields: <https://docs.nuget.org/create/nuspec-reference> In regards to the summary it says it is > > A short description of the package. If specified, this shows up in the middle pane of the Add Package Dialog. If not specified, a truncated version of the description is used instead. > > > Does anyone know the max length of the summary, description, and how many characters from the description will be used if the summary is not provided?
2015/10/21
[ "https://Stackoverflow.com/questions/33264005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/68905/" ]
There is no maximum length of the summary or description. If no summary is used then all of the description is used. However what gets displayed is based on the size of the Manage Packages dialog, the size of characters used in the text, whether the row is selected and the Install button is showing, whether you are using Visual Studio 2015 or an older version. So there is not a defined number of characters defined as the maximum length.
296,402
Are there any synonyms for the word "high-concept"? Here is the sentence:"The same goes for some of the high concept scenes in the film – I was often creating a new mix down nearly every single day with new ideas and sounds for him and the picture editors to review and reflect on". According to dictionary it means "a simple and often striking idea or premise, as of a story or film, that lends itself to easy promotion and marketing" but I couldn't find an appropriate synonym of it.
2015/12/28
[ "https://english.stackexchange.com/questions/296402", "https://english.stackexchange.com", "https://english.stackexchange.com/users/142638/" ]
***Devotement*** is an outdated, less common variant of devotion: > > * The action of devoting, or fact of being devoted; devotion, dedication. > + **1604** Shakes. Oth. ii. iii. 322 *He hath deuoted, and giuen vp himselfe to the Contemplation, marke, and deuotement of her parts and Graces.* > + ***1852*** Wayland Mem. Judson (1853) i 29 *His own personal devotement to the missionary cause.* > > > OED [Ngram](https://books.google.com/ngrams/graph?content=devotement%2C%20devotion%20&year_start=1800&year_end=2008&corpus=15&smoothing=3&share=&direct_url=t1%3B%2Cdevotement%3B%2Cc0%3B.t1%3B%2Cdevotion%3B%2Cc0): *devotement vs devotion.* [Ngram](https://books.google.com/ngrams/graph?content=devotement&year_start=1800&year_end=2008&corpus=15&smoothing=3&share=&direct_url=t1%3B%2Cdevotement%3B%2Cc0): *devotement.* It origin is probably due to the practice of adding the suffix -ment to verbs to form nouns which starred from the 16th century: ***[-ment](http://www.etymonline.com/index.php?term=-ment&allowed_in_frame=0)*** : > > * ***suffix forming nouns, originally from French and representing Latin -mentum, which was added to verb stems sometimes to represent the result or product of the action.*** French inserts an -e- between the verbal root and the suffix (as in commenc-e-ment from commenc-er; with verbs in ir, -i- is inserted instead (as in sent-i-ment from sentir). > * ***Used with English verb stems from 16c.*** for example merriment, which also illustrates the habit of turning -y to -i- before this suffix). > > > (Etymonline) ***[Devotion](http://www.etymonline.com/index.php?term=devotion&allowed_in_frame=0)*** (n.) has an older origin:. > > * ***early 13c., from Old French devocion "devotion, piety," from Latin devotionem*** (nominative devotio), noun of action from past participle stem of devovere "dedicate by a vow, sacrifice oneself, promise solemnly," > > > From which ***[devote](http://www.etymonline.com/index.php?term=devote&allowed_in_frame=0)*** (verb) > > * ***1580s, from Latin devotus,*** past participle of devovere (see devotion). Second and third meanings in Johnson's Dictionary (1755) are "to addict, to give up to ill" and "to curse, to execrate; to doom to destruction." > > > and later (17th century) ***"devotement".***
579,665
Look at these two questions: Has your brother graduated from college? Did your brother graduate from college? Now, both of these questions seem fine to me, but I obviously know they are a little different. However, I can’t seem to explain what the slight difference is between these grammatical sentences. I know that when I use the present perfect, I am expecting an answer of “yes, he has” or “no he hasn’t “ with no specific details of exactly when in the past. But with the simple past, usually there is a specific time in the past and it conveys finality and that it is completely finished at a specific point that the speaker knows the time reference when he/she asks that question. Is there anything else I am missing? Edit: Both are acceptable to my ear but what would people assume differently if they hear one or the other? Or is it the same? Edit: Are both acceptable to use depending on the circumstances?
2021/12/05
[ "https://english.stackexchange.com/questions/579665", "https://english.stackexchange.com", "https://english.stackexchange.com/users/389274/" ]
I will answer for US English (not sure if this will hold in UK English). If I don't have any prior knowledge about the brother, I'd ask, "Did your brother go to college?" (Depending on where the conversation went from there, I might ask, "Did he get his degree?".) I would probably only ask, "Has your brother graduated from college?" if I happen to know that the brother has some college studies under his belt. Otherwise, I'd ask, "Does your brother have a college degree?" or "Did your brother go to college?" or possibly "Did your brother graduate from college?". The latter form doesn't sound very conversational, though. If you want to get more authentic you'll want to take into account that nowadays the person might stop after a two-year degree (Associates) -- it's complicated! If that doesn't address your question, please clarify.
24,560,942
I am attempting to model an existing MSSQL table in SailsJS. Unsurprisingly the tables in the existing database have a createdAt and updatedAt column similar to what is generated by the SailsJS framework. **Is there a way to assign the value of the property generated by the SailsJS framework to an attribute that I have defined?** For example: ``` attributes: { ... creationDate:{ columnName:'cre_dt', type:'datetime', defaultsTo: this.createdAt } ... } ```
2014/07/03
[ "https://Stackoverflow.com/questions/24560942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2418179/" ]
No, but you can turn off the auto-generated property entirely and use your own: ``` autoCreatedAt: false, autoUpdatedAt: false, attributes: { creationDate: { columnName: 'cre_dt', type: 'datetime', defaultsTo: function() {return new Date();} }, updateDate: { columnName: 'upd_dt', type: 'datetime', defaultsTo: function() {return new Date();} } }, //Resonsible for actually updating the 'updateDate' property. beforeValidate:function(values,next) { values.updateDate= new Date(); next(); } ``` See the [Waterline options doc](https://github.com/balderdashy/waterline#options).
446,390
I'm modeling credit fraud, where I have a small number of samples that result in fraud (1), and most samples that are not fraud (0). I am creating a models for detecting fraud based on new data. I'm using the following models: logistic regression, K-nn, Support Vector Classifier and decision tree. The dataset is very similar to this: kaggle.com/mlg-ulb/creditcardfraud I performed random undersampling on the data to get a 1:1 ratio. This made my models perform a lot better, but since the undersampling is performed randomly every time, I get a slightly different result because of the chosen samples. Is there a way to find out which of the 8200 majority class samples are best to use in the undersampled data? I was hoping to figure out which these are and only use them with the 800 positive samples on my undersampled dataset.
2020/01/25
[ "https://stats.stackexchange.com/questions/446390", "https://stats.stackexchange.com", "https://stats.stackexchange.com/users/265242/" ]
The methods you list in the question are discriminative (i.e. you do not indicate that you used the one-class variety e.g. of SVM). Have you considered [one-class classification](https://en.wikipedia.org/wiki/One-class_classification)? One class classification is probably better suited for credit fraud detection than discriminative classification and as a side effect it does (by construction) not have any difficulties with class imbalance. One-class classification is good for situatione where * a\* well-defined ("positive") class is to be separated from cases that do not belong to this class. + well-defined means that the data points of this class form a (or maybe few separate) clouds, but we need not expect "surprises" in future cases (this is really not different from how we think of classes in discriminative settings) + and there are sufficient cases available from this class + \* there can be several such classes, they are treated separately. * cases that do not belong to the positive class (aka the negative class) are ill-defined: + We cannot (or need not be able to) describe those cases better than saying they do not belong to the positive class. + There may be many reasons (classes) of cases that do not belong to the positive class + any new case that does not belong to the positive class may not belong there for an entirely new reason. + Side note: specific known classes within the negatives can be modeled as their own class - this does not affect the performance of the recognition of the positive class in any way. * In one-class classification, a case can belong to more than one class (consider medical diagnosis: a patient may have several diseases that are independent of each other). Your task sounds to me as if the no-fraud cases are a prime example for a positive class. In addition, if you have examples of specific known types of fraud, you can also model them as their own class. If only few cases are available, recognition of that that (sub)class of fraud will of course be uncertain. But this will not disturb the performance of recognizing no-fraud cases.
5,558
I often run into various licenses for commercial software, and large part of that software has a different text saying the same thing. With license proliferation being a known thing in OSS, are/were there any attempts to fight it in commercial sphere? If not, **what are the unique concerns within the FLOSS community** that made deproliferation desirable there, but not in the domain of proprietary software? (Or if there has been such an effort that I haven't heard of, what distinguishes FLOSS such that the FLOSS deproliferation effort been so much more visible?)
2017/06/02
[ "https://opensource.stackexchange.com/questions/5558", "https://opensource.stackexchange.com", "https://opensource.stackexchange.com/users/5636/" ]
There are attempts to create some standard or templates in other areas, but none that I know in commercial licenses agreements. If there were, not every contract would end up being different! An example of related effort is [common form](https://github.com/commonform) for contract [standardization](https://commonform.org/) and it may contain some licensing-related terms. Now the thing is that proliferation is rather small in the FOSS world... there are about a 1000 significant license variations (and 5 to 10 times more variations on notices..) .... whereas there are likely 10 or 100 times more variants of commercial license contracts. That's the price to pay to paying: each license you pay for is also likely to be a whole new shiny thing. You later asked: > > what are the unique concerns within the FLOSS community that made deproliferation desirable there [...]? > > > With FLOSS, one goal is to facilitate and foster reuse. Yet every package is also licensed and there are subtle license compatibility issues. If every package had a different license building complex system from FLOSS would be a nightmare (it is hard enough as it is) so naturally communities around a programming language, platform or framework have evolved to use similar or the same licensing: this makes reuse much simpler. For instance a lot of Perl project use the "Same as Perl" license, several C/C++-based userland utilities use a combo of LGPL for the library and GPL for the command line tools, several Java-based packages built on or reusing Apache-provided packages use the Apache license, some foundations or larger orgs even enforce this for simplicity and sanity such as the Apache or the Eclipse Foundations. Also FLOSS license terms are not negotiable: you either take it or pass. So there is usually no possibility of per-user variation. In contrast, the goal of commercial software is not only to maximize usage but to maximize the financial gain. Since every contract needs some transaction (e.g. some signature or agreement and some money transfer) there is not much incentive per se to facilitate these transactions across vendors. Furthermore, each contract is eventually negotiable and customers may want special terms which further increase the number of variations. Yet, some vendors (such as Atlassian at least historically) have always used very standard, non-negotiable licensing terms that apply across all their product lines to avoid license proliferation across their customers.
15,245,767
I have just merged two branches 'branch1' and 'branch2'. The problem is that it is now a mess with a lot of conflicts, with sometimes duplicate contents (is it possible ??). What I want to do is to force for some files from 'branch1' to be merged against 'branch2' and conversely to force some files from 'branch2' to be merged against 'branch1', knowing I am now on 'branch1'. Is it possible ? Update : there seems to be problem with git-merge ? Suppose I keep the branch1 version, then ``` echo $this->fetch('prehome.html'); die; ``` would appear two times, see : ``` protected function prehomepage() { $var = 'myvar'; echo $this->fetch('prehome.html'); die; } <<<<<<< HEAD $this->mySmarty->assign('title', 'Primagora'); echo $this->fetch('prehome.html'); die; } /** * Generate the campaign block for the general sidebar, called through AJAX. */ protected function getCampaignBlock() { $from = Utils::fromGet('from'); echo $this->getCampaignSidebarBlock($from); die(); } ======= /** * Generate the campaign block for the general sidebar, called through AJAX. */ protected function getCampaignBlock() { $from = Utils::fromGet('from'); echo $this->getCampaignSidebarBlock($from); die(); } >>>>>>> branch2 ```
2013/03/06
[ "https://Stackoverflow.com/questions/15245767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1275959/" ]
On a merge with conflicts (if `git config merge.conflictstyle diff3` is set) , you can: * ignore that merge and keep your original version (from `branch1`): ``` git show :2:full_path > file # or git checkout-index --stage=2 -- file ``` * ignore that merge and keep the other version (from `branch2`): ``` git show :3:full_path > file # or git checkout-index --stage=3 -- file ``` From there, `git add` and `git commit`.
1,526,510
What Is the difference between how the char datatype is stored or represented in 32bit vs 64bit in C?
2009/10/06
[ "https://Stackoverflow.com/questions/1526510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184503/" ]
There is no difference. One char occupies one byte. One byte has CHAR\_BIT bits. ``` #include <limits.h> #include <stdio.h> int main(void) { printf("a char occupies 1 byte of %d bits.\n", CHAR_BIT); return 0; } ```
32,176,761
Not much familiar with JQuery; I want to get id of form element in jquery which is located in following location ``` <body> <div id="boxDialog"> </div> <div class="container"> <div class="header"> Many Tables and divs </div> </div> <form id="approval"></form> Jquery: : : alert($("body.form").attr("id")); ``` Fiddle: <https://jsfiddle.net/j32f9128/>
2015/08/24
[ "https://Stackoverflow.com/questions/32176761", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1382647/" ]
**Problem:** `body.form` will select the `body` element having class of `form`, which doesn't exists so returns `undefined`. **Solution:** Use space between the `body` and `form` and remove `.`. Using space, the `form` element will be searched in `body`. ``` alert($("body form").attr("id")); ``` You can also ommit `body` here as all the `forms` are nested inside `body`. ``` alert($("form").attr("id")); ``` If you want to get the `id` of **first** form element, you can use `first()`. ``` alert($("form").first().attr("id")); ``` Or you can also ``` alert($("form:first").attr("id")); ``` [**Demo**](https://jsfiddle.net/tusharj/j32f9128/1/)
71,698,080
I have a screen like this: [![enter image description here](https://i.stack.imgur.com/TbgZK.png)](https://i.stack.imgur.com/TbgZK.png) There is a `checkBox` right above the button. When I click on the `checkBox`, it is ticked; If it's already ticked, I want it unticked. I wrote the following code for this: ``` Checkbox( checkColor: Colors.white, value: isChecked, onChanged: (bool value) { setState(() { isChecked = value; }); }, ), ``` --- I put the checkBox here inside the `showModalBottomSheet`. When I click the checkbox, it ticks but does not appear. I tried to close and open the `showModalBottomSheet` if it is ticked. I clicked it while `showModalBottomSheet` was open, then I closed and reopened `showModalBottomSheet` and saw that it was ticked. I saw that when `showModalBottomSheet` is open, it does not click, I need to close it. `showModalBottomSheet` codes: ``` FlatButton( child: Text("Hesap Oluştur", style: TextStyle(color: Colors.blue[400], fontSize: 18, fontFamily: "Roboto-Thin"),), onPressed: () async { await showModalBottomSheet( isScrollControlled: true, shape: RoundedRectangleBorder( borderRadius: BorderRadius.only(topLeft: Radius.circular(20), topRight: Radius.circular(20)), ), context: context, builder: (context) { return FractionallySizedBox( heightFactor: 0.75, child: Column( children: [ Padding( padding: EdgeInsets.all(15), child: Column( children: [ Text("Hesap Oluştur", style: TextStyle(fontSize: 25, fontFamily: "Roboto-Bold"),), SizedBox(height: 8), Text("Hesap oluşturmak oldukça basittir. Bilgilerini gir, hesabını oluştur.",style: TextStyle(fontSize: 18, fontFamily: "Roboto-Thin"), textAlign: TextAlign.center,), SizedBox(height: 10), Divider(thickness: 1,), SizedBox(height: 10), TextFormField( decoration: InputDecoration( hintText: "E-posta", prefixIcon: Icon(Icons.mail) ), style: TextStyle(fontSize: 18), ), SizedBox(height: 15), TextFormField( decoration: InputDecoration( hintText: "Ad-soyad", prefixIcon: Icon(Icons.person) ), style: TextStyle(fontSize: 18), ), SizedBox(height: 15), TextFormField( obscureText: true, decoration: InputDecoration( hintText: "Şifre", prefixIcon: Icon(Icons.lock) ), style: TextStyle(fontSize: 18), ), SizedBox(height: 15), TextFormField( obscureText: true, decoration: InputDecoration( hintText: "Şifreyi doğrula", prefixIcon: Icon(Icons.lock) ), style: TextStyle(fontSize: 18), ), Checkbox( checkColor: Colors.white, value: isChecked, onChanged: (bool value) { setState(() { isChecked = value; }); }, ), RaisedButton( child: Padding( padding: const EdgeInsets.only(right: 85, left: 85, top: 12, bottom: 12), child: Text("Create account", style: TextStyle(color: Colors.white, fontSize: 20, fontFamily: "Roboto-Thin"),), ), color: Colors.blue[400], textColor: Colors.white, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(30.0), ), onPressed: () { //Navigator.push(context, MaterialPageRoute(builder: (context) => HomePage())); }, ), ], ), ) ], ), ); } ); }, ), ``` How can I solve this problem? I appreciate the help in advance.
2022/03/31
[ "https://Stackoverflow.com/questions/71698080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18003111/" ]
Hi Emir Bolat you need to wrap your "FractionallySizedBox" with "statefulBuilder" and that's it. Thanks
53,655,563
I'm trying to parse an XML file using "lxml" module in Python. My xml is: ``` <?xml version="1.0"?> <root xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <GEOMdata> <numEL>2</numEL> <EL> <isEMPTY>true</isEMPTY> <SECdata> <SEC> <Z>10.00</Z> <A>20.00</A> <P>30.00</P> </SEC> <SEC> <Z>40.00</Z> <A>50.00</A> <P>60.00</P> </SEC> </SECdata> </EL> <EL> <isEMPTY>false</isEMPTY> <SECdata> <SEC> <Z>15.00</Z> <A>25.00</A> <P>35.00</P> </SEC> <SEC> <Z>45.00</Z> <A>55.00</A> <P>65.00</P> </SEC> </SECdata> </EL> </GEOMdata> </root> ``` I want to write a text file for each "EL" reporting isEMPTY value and a list of Z,A,P values. Despite the I/O I don't understand how to access this file. For the moment I wrote that code: ``` from lxml import etree parser = etree.XMLParser(encoding='UTF-8') tree = etree.parse("TEST.xml", parser=parser) for ELtest in tree.xpath('/root/GEOMdata/EL'): print (ELtest.findtext('isEMPTY')) ``` and the output is correct: ``` true false ``` Now I don't know how to access the children element Z,A,P "inside" ELtest. Thanks for your kind help. EDIT: The desired output is a formatted file like this: ``` 1 true # Z A P # 10 20 30 40 50 60 2 false # Z A P # 15 25 35 45 55 65 ```
2018/12/06
[ "https://Stackoverflow.com/questions/53655563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7252497/" ]
[Date Functions](https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-DateFunctions): Use `datediff` and `case` ``` select Name,startdate,enddate, case when datediff(enddate,startdate) < 60 then 1 else 0 end flag from table ``` If you are comparing the previous row's enddate, use `lag()` ``` select Name,startdate,enddate, case when datediff(startdate,prev_enddate) < 60 then 1 else 0 end flag from ( select Name,startdate,enddate, lag(endate) over(partition by Name order by startdate,enddate) as prev_enddate from table ) t ```
66,457,672
I came across one issue that I cannot create SSRS databases on Azure SQL Database, netiher I can use the migrated databases of report server in the SSRS Config manager, can anyone explain why is this a limitation and something like Managed Instance or Azure SQL VM is needed in this case? Is there no other way of configuring Azure SQL Database with SSRS?
2021/03/03
[ "https://Stackoverflow.com/questions/66457672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7790172/" ]
Azure SQL database didn't explain why SSRS is not supported in Azure SQL database. I think the reason the that [Azure SQL database](https://learn.microsoft.com/en-us/azure/azure-sql/azure-sql-iaas-vs-paas-what-is-overview) is PAAS and different between IAAS: Azure MI and SQL server in VMS: [![enter image description here](https://i.stack.imgur.com/y5scJ.png)](https://i.stack.imgur.com/y5scJ.png) And for now, there is no way to configure SSRS for Azure SQL database. SQL database product team confirmed this. Ref this [feedback](https://feedback.azure.com/forums/217321-sql-database/suggestions/7955331-support-sql-server-reporting-service): * "**Thanks for your feedback here. You can do SSRS today in an Azure VM. I’m closing this as we have no plans in SQL DB to significantly grow it’s scope to SSRS.**" If you still want to SSRS, you need to choose Azure SQL managed instance or SQL Server in VMs. HTH. [![enter image description here](https://i.stack.imgur.com/Q6Gl4.png)](https://i.stack.imgur.com/Q6Gl4.png)
58,633,156
I tried installing js-cookie (<https://github.com/js-cookie/js-cookie>) using npm in my Laravel project, but I keep getting the same *ReferenceError: Cookies is not defined* error. It works just fine with a local copy of js-cookie and via CDN, but I would like to figure out why it doesn't work via npm. **What I've tried:** ``` npm i js-cookie npm i js-cookie --save npm i js-cookie --save-dev ``` followed by ``` npm run dev ``` **What I get as a result:** - js-cookie v 2.2.1 gets included in my package.json under dependencies or devDependencies - js-cookie appears under node\_mnodules - *ReferenceError: Cookies is not defined* while trying to use any Cookies functions Any help would be greatly appreciated! **Edit 1 - including all my code** My master.blade.php looks like this: ``` <!DOCTYPE html> <html> <head> <meta name="csrf-token" content="{{ csrf_token() }}"> <title>@yield('title')</title> <link rel="stylesheet" type="text/css" href="{{ asset('css/app.css') }}"> <link rel="stylesheet" type="text/css" href="{{ asset('css/nightmode-toggle.css') }}"> <script type="text/javascript" src="{{ asset('js/app.js') }}"></script> <script type="text/javascript" src="{{ asset('js/nightmode-toggle.js') }}"></script> </head> <body id="mybody"> @include('layouts.navbar') <div class="content"> @yield('content') </div> </body> </html> ``` The content of the nightmode-toggle.css are just a few classes I toggle on and off while clicking a "Nightmode" checkbox: ``` body.night { background:black; color:white; } .navbar.night { background-color:black; color:white; } etc... ``` The content of nightmode-toggle.js: ``` $(document).ready(function () { if (Cookies.get('nightmode-toggle') != 'on' && Cookies.get('nightmode-toggle') != 'off') { Cookies.set('nightmode-toggle', 'off'); } if (Cookies.get('nightmode-toggle') == 'off' && $('body').hasClass('night')) { $('body').toggleClass('night'); $('.navbar').toggleClass('night'); etc... } else if (Cookies.get('nightmode-toggle') == 'on' && !$('body').hasClass('night')) { $('body').toggleClass('night'); $('.navbar').toggleClass('night'); etc... } $('#nightmode-toggle').click(function () { if (Cookies.get('nightmode-toggle') == 'off') { Cookies.set('nightmode-toggle', 'on'); $('body', ).toggleClass('night'); $('.navbar').toggleClass('night'); etc... } else { Cookies.set('nightmode-toggle', 'off'); $('body').toggleClass('night'); $('.navbar').toggleClass('night'); etc... } $.ajax({ type: "POST", url: "/toggle", success: function () { }, error: function () { alert('Could not switch to Night Mode for some reason! Please try again later.'); } }); }) }); ``` As I said earlier, if I include a local js-cookie.js file in the header, like so ``` <script type="text/javascript" src="{{ asset('js/js-cookie.js') }}"></script> ``` or if I include CDN in the header, like so ``` <script src="https://cdn.jsdelivr.net/npm/js-cookie@beta/dist/js.cookie.min.js"></script> ``` everything works perfectly fine aka cookies get recorded correctly and classes change depending on the cookie. But I really want to figure out how to include js-cookie using npm as instructed by the developer.
2019/10/30
[ "https://Stackoverflow.com/questions/58633156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11923840/" ]
You need to import the library in `bootstrap.js` or `app.js` as an ES6 module as per [the docs](https://github.com/js-cookie/js-cookie#es-module) ```js import Cookies from 'js-cookie' ``` Then use it anywhere else like so ```js Cookies.set('foo', 'bar') ```
38,846,292
I have set up a search form for my database. When I search and results are found a message is echoed below the search form. For instance, 10 records found, 0 records found. How can I get that message to disappear if the search form field is blank/empty. Currently it displays **15 records found** for a blank/empty search field. Which is all the database records. Thanks for any help. **Form:** ``` <form action="" method="post"> <input type="text" name="search_box" value="<?php if (isset($_POST['search_box'])) echo $_POST['search_box']; ?>" placeholder="Search here ..."/> <input value="Search" name="search" type="submit" /><br> </form> ``` **PHP:** ``` <?php $count = mysqli_num_rows($result); if($count > 0){ echo $count . " Records Found"; }if($count == 0){ echo "0 Records Found"; }if($count == ""){ echo ""; } ?> ``` **Query:** ``` //Retrieve the practice posts from the database table $query = "SELECT * FROM practice"; //check if search... button clicked, if so query fields if(isset($_POST['search'])){ $search_term = trim($_POST['search_box']); $query .= " WHERE title = '{$search_term}'"; $query .= " or subject LIKE '%{$search_term}%'";} ```
2016/08/09
[ "https://Stackoverflow.com/questions/38846292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2494593/" ]
``` <?php //Retrieve the practice posts from the database table $query = "SELECT * FROM practice"; //check if search... button clicked, if so query fields if(isset($_POST['search'])){ $search_term = trim($_POST['search_box']); $query .= " WHERE title = '{$search_term}'"; $query .= " or subject LIKE '%{$search_term}%'"; //execute your query $result = $dbconnect->query($query); $count = mysqli_num_rows($result); if($count > 0){ echo $count . " Records Found"; } if($count == 0){ echo "0 Records Found"; } } else { // it is mean your search box value($_POST['search']) is empty, so it will echo null value echo $_POST['search']; } ?> ``` please try, hope will save your day :D
20,024,531
I need this file for tutorials, but I can't find it anywhere on the internet. Help somebody?
2013/11/16
[ "https://Stackoverflow.com/questions/20024531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2943202/" ]
Any tutorial that uses `iostream.h` is twenty years out of date; that header was used in pre-standard C++, but has never been part of the ISO standard. Find a newer tutorial; one that uses `iostream`.
5,649
Could a satellite, without too much fuel consumption for station keeping, orbit the Earth so that it always has a line of sight to the Moon? It would need a near polar orbit which precesses in tandem with the Moon's orbit around Earth. Wouldn't that be the perfect communication satellite orbit for constantly staying in touch with Lunar missions? Have any satellites used such an orbit and does that type of orbit have a three letter name? EDIT: I'm looking for the possibility of a satellite orbiting Earth's poles so that it can always have contact with the Earth facing side of the Moon, and with satellites in lunar polar orbit which precess so that they remain in line of sight with this satellite (and the rotating Earth). A potential use for this would be that such a polar Earth satellite would have a relatively small altitude and be able to relay data to Earth more easily than having to use something like the Deep Space Network spread across the equator.
2014/10/20
[ "https://space.stackexchange.com/questions/5649", "https://space.stackexchange.com", "https://space.stackexchange.com/users/1457/" ]
<http://en.wikipedia.org/wiki/Lagrangian_point> A satellite orbiting at the L1 point or L2 point would be in constant contact with the moon. Unfortunately, neither of these are particularly useful for keeping in contact with a lunar mission. The L1 point is between the earth and the moon, and would offer no advantages over just putting the reciever on earth. The L2 point is on the far side of the moon, and would therefore not be able to communicate with earth. <http://ntrs.nasa.gov/archive/nasa/casi.ntrs.nasa.gov/19680015886.pdf> This article seems to be exactly what you want. They conclude that a satellite near L2 would work.
46,580,981
I have a requirement to do the following: 1. Get a list of "lines" by calling an internal function (getLines()). 2. Select the first line, perform an action 3. After the previous action finishes, select the next line and do the same action 4. Repeat for all lines (3-20 depending on user) I have the following code in place: ``` App.Lines = response.data; for (var _i = 0; _i < App.Lines.length; _i++) { var makeCallPromise = new Promise( function(resolve, reject) { Session.connection.ol.makeCall(App.Lines[_i], callBackFunction(response) { //this can take up to 30 seconds to respond... resolve(response.data); }, errorCallBackFunction(message) { reject(message.error); }, bareJid); } ) makeCallPromise.then(function(fulfilled) { console.log("PROMISE WORKED!!!!!", fulfilled); }) .catch(function(error) { console.log("PROMISE FAILED!!!!!", error); }); } ``` My hope was that the loop would wait to resolve the promise before it continued the loop, however, that's not the case. My question is whether or not it's possible to halt the loop until the resolution is complete. Note - I am using the bluebird JS library for promises. Thank you! Kind Regards, Gary
2017/10/05
[ "https://Stackoverflow.com/questions/46580981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2265237/" ]
I don't know about bluebird, but you can do something like that to create some kind of for loop that waits for each promise to end before the next iteration. Here is a generic example, it could certainly be optimized, it's just a quick attempt: ``` var i = 0; var performAsyncOperation = function(operationNumber) { return new Promise(function(resolve, reject){ console.log('Operation number', operationNumber); resolve(); }); } var chainAsyncOperations = function() { if(++i < 10) { return performAsyncOperation(i).then(chainAsyncOperations); } }; performAsyncOperation(i).then(chainAsyncOperations); ``` Hoping this will help you ;)
240,058
I need a timer tick with 1ms resolution under linux. It is used to increment a timer value that in turn is used to see if various Events should be triggered. The POSIX timerfd\_create is not an option because of the glibc requirement. I tried timer\_create and timer\_settimer, but the best I get from them is a 10ms resolution, smaller values seem to default to 10ms resolution. Getittimer and setitimer have a 10 ms resolution according to the manpage. The only way to do this timer I can currently think of is to use clock\_gettime with CLOCK\_MONOTONIC in my main loop an test if a ms has passed, and if so to increase the counter (and then check if the various Events should fire). Is there a better way to do this than to constantly query in the main loop? What is the recommended solution to this? The language I am using is plain old c **Update** I am using a 2.6.26 Kernel. I know you can have it interrupt at 1kHz, and the POSIX timer\_\* functions then can be programmed to up to 1ms but that seems not to be reliable and I don't want to use that, because it may need a new kernel on some Systems. Some stock Kernel seem to still have the 100Hz configured. And I would need to detect that. The application may be run on something else than my System :) I can not sleep for 1ms because there may be network events I have to react to. **How I resolved it** Since it is not that important I simply declared that the global timer has a 100ms resolution. All events using their own timer have to set at least 100ms for timer expiration. I was more or less wondering if there would be a better way, hence the question. **Why I accepted the answer** I think the answer from freespace best described why it is not really possible without a realtime Linux System.
2008/10/27
[ "https://Stackoverflow.com/questions/240058", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6510/" ]
Polling in the main loop isn't an answer either - your process might not get much CPU time, so more than 10ms will elapse before your code gets to run, rendering it moot. 10ms is about the standard timer resolution for most non-[realtime operating systems](http://en.wikipedia.org/wiki/Real-time_operating_system) (RTOS). But it is moot in a non-RTOS - the behaviour of the scheduler and dispatcher is going to greatly influence how quickly you can respond to a timer expiring. For example even suppose you had a sub 10ms resolution timer, you can't respond to the timer expiring if your code isn't running. Since you can't predict when your code is going to run, you can't respond to timer expiration accurately. There is of course realtime linux kernels, see <http://www.linuxdevices.com/articles/AT8073314981.html> for a list. A RTOS offers facilities whereby you can get soft or hard guarantees about when your code is going to run. This is about the only way to reliably and accurately respond to timers expiring etc.
8,114,131
concerning android development, I'm simply trying to create an SQL database when the activity is launched for the first time (using preferences). The second time the activity is launched it should retrieve the data from the database and output a log message. Ive managed to launch the activity for the first time (im assuming the database was created here) but the second time i get an IllegalStateException error: get field slot from row 0 to col -1 failed. Not really sure where i went wrong here. can someone please check? Thanks Main class ``` public class MainMenu extends Activity implements OnClickListener{ private ModulesDbAdapter mpDbHelper; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //create database here SharedPreferences initialPref = getSharedPreferences("INITIAL", 0); boolean firsttimer = initialPref.getBoolean("INITIAL", false); if (!firsttimer){ //create database here mpDbHelper = new ModulesDbAdapter(this); mpDbHelper.open(); long id1 = mpDbHelper.createReminder("Hello1", "Test 1", "Date1"); long id2 = mpDbHelper.createReminder("Hello2", "Test 2", "Date2"); long id3 = mpDbHelper.createReminder("Hello3", "Test 3", "Date3"); /*Cursor c = mpDbHelper.fetchModules((String)"CS118"); Log.d("TESTING",c.getString(c.getColumnIndex("KEY_MOD_NAME")));*/ //get boolean preference to true SharedPreferences.Editor editorPref = initialPref.edit(); editorPref.putBoolean("INITIAL", true); editorPref.commit(); }else { fetchData(); } } private void fetchData(){ mpDbHelper = new ModulesDbAdapter(this); mpDbHelper.open(); long input = 2; Cursor c = mpDbHelper.fetchReminder(input); startManagingCursor(c); Log.d("TESTING",c.getString(c.getColumnIndex("KEY_BODY"))); } /*@Override protected void onPause() { super.onPause(); mpDbHelper.close(); } @Override protected void onStop() { super.onPause(); mpDbHelper.close(); }*/ } } ``` Adapter class ``` public class ModulesDbAdapter { private static final String DATABASE_NAME = "data"; private static final String DATABASE_TABLE = "reminders"; private static final int DATABASE_VERSION = 1; public static final String KEY_TITLE = "title"; public static final String KEY_BODY = "body"; public static final String KEY_DATE_TIME = "reminder_date_time"; public static final String KEY_ROWID = "_id"; private DatabaseHelper mDbHelper; private SQLiteDatabase mDb; //defines the create script for the database private static final String DATABASE_CREATE = "create table " + DATABASE_TABLE + " (" + KEY_ROWID + " integer primary key autoincrement, " + KEY_TITLE + " text not null, " + KEY_BODY + " text not null, " + KEY_DATE_TIME + " text not null);"; //Context object that will be associated with the SQLite database object private final Context mCtx; //The Context object is set via the constructor of the class public ModulesDbAdapter(Context ctx) { this.mCtx = ctx; } //helps with the creation and version management of the SQLite database. private static class DatabaseHelper extends SQLiteOpenHelper { //call made to the base SQLiteOpenHelper constructor. This call creates, opens, and/or manages a database DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(DATABASE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion,int newVersion) { // Not used, but you could upgrade the database with ALTER // Scripts } } //now create the database by calling the getReadableDatabase() public ModulesDbAdapter open() throws android.database.SQLException { mDbHelper = new DatabaseHelper(mCtx); mDb = mDbHelper.getWritableDatabase(); return this; } //close the database public void close() { mDbHelper.close(); } public long createReminder(String title, String body, String reminderDateTime) { ContentValues initialValues = new ContentValues(); initialValues.put(KEY_TITLE, title); initialValues.put(KEY_BODY, body); initialValues.put(KEY_DATE_TIME, reminderDateTime); //insert row into database return mDb.insert(DATABASE_TABLE, null, initialValues); } public boolean deleteReminder(long rowId) { return mDb.delete(DATABASE_TABLE, KEY_ROWID + "=" + rowId, null) > 0; } //utilizes the query() method on the SQLite database to find all the reminders in the system public Cursor fetchAllReminders() { return mDb.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE, KEY_BODY, KEY_DATE_TIME}, null, null, null, null, null); } public Cursor fetchReminder(long rowId) throws SQLException { Cursor mCursor = mDb.query(true, DATABASE_TABLE, new String[] {KEY_ROWID, KEY_TITLE, KEY_BODY, KEY_DATE_TIME}, KEY_ROWID + "=" + rowId, null, null, null, null, null); if (mCursor != null) { mCursor.moveToFirst(); } return mCursor; } public boolean updateReminder(long rowId, String title, String body, String reminderDateTime) { ContentValues args = new ContentValues(); args.put(KEY_TITLE, title); args.put(KEY_BODY, body); args.put(KEY_DATE_TIME, reminderDateTime); return mDb.update(DATABASE_TABLE, args, KEY_ROWID + "=" + rowId, null) > 0; } // The SQLiteOpenHelper class was omitted for brevity // That code goes here. ``` }
2011/11/13
[ "https://Stackoverflow.com/questions/8114131", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1044502/" ]
The error is simple. You've defined KEY\_BODY as a static string constant value in the DbAdapter class, but you've used the string literal "KEY\_BODY" in your access code. ``` Log.d("TESTING",c.getString(c.getColumnIndex("KEY_BODY"))); ``` should be ``` Log.d("TESTING",c.getString(c.getColumnIndex(ModulesDbAdapter.KEY_BODY))); ```
41,539
I'm writing a book largely based on a OASIS open standard. I assume this would constitute derivative work. I wondering about the following phrasing in the copyright. > > The document(s) and translations of it may be copied and furnished to others, and derivative works that comment on or otherwise explain it or assist in its implementation may be prepared, copied, published and distributed, in whole or in part, without restriction of any kind, provided that the above copyright notice and this paragraph are included on all such copies and derivative works... > > > If I do a derivative work it says the copy right notice and paragraph needs to be included. Does that mean that I just add this as a attribution att the end, or will this copyright then cover the entirety of the book and allow others to copy it freely? Copyright notice in full <https://www.oasis-open.org/committees/ciq/copyright.shtml>
2019/05/29
[ "https://law.stackexchange.com/questions/41539", "https://law.stackexchange.com", "https://law.stackexchange.com/users/25931/" ]
Whoever wrote this standard didn't write your book and therefore has no copyright on it, except for the parts derived from the standard. So it doesn't make sense that a copyright notice would claim copyright on your book. Just including the copyright notice would only cause confusion, because a copyright needs to be formally transferred. (Even with the notice, you would still be copyright holder. But if anyone creates a derived work assuming the notice - which you put there - refers to the whole book, you'd have a very hard time claiming damages. So it's a bad idea to include it). I would write "This book is based on the so-and-so standard" followed by the copyright notice and license, which makes it clear that the copyright notice and license refer to the standard, not your book. Do the wording a bit more careful then I did, perhaps consult a lawyer who is better than me and you at finding the exact right words.
33,158
How do I search files, some of which might be directories (in this case recursively) for a given string? I'd like to search source files for a class definition, so it would also be great if there was the name of the containing file before each output string.
2009/06/29
[ "https://serverfault.com/questions/33158", "https://serverfault.com", "https://serverfault.com/users/3320/" ]
You could use grep: ``` grep -rn 'classname' /path/to/source ``` This will also print the line number next to each match. Case insensitive: ``` grep -rin 'classname' /path/to/source ``` Search non-recursively in all cpp files: ``` grep -n 'classname' /path/to/source/*.cpp ```
71,924,096
I have a dataset containing various fields of users, like dates, like count etc. I am trying to plot a histogram which shows like count with respect to date, how should I do that? The dataset: [![enter image description here](https://i.stack.imgur.com/3cheh.png)](https://i.stack.imgur.com/3cheh.png)
2022/04/19
[ "https://Stackoverflow.com/questions/71924096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15563833/" ]
Assuming you want to plot number of public likes by date, you could do something like this: ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt df = pd.read_csv('analysis.csv') # convert text column to date time and keep only the date part df['created_at'] = pd.to_datetime(df['created_at']) df['created_at'] = df['created_at'].dt.date # group by date taking the sum of public_metrics.like_count df1 = df.groupby(['created_at'])['public_metrics.like_count'].sum().reset_index() df1 = df1.set_index('created_at') # plot and show df1.plot() plt.show() ``` And this is the output you will get [![Plotting likes by date](https://i.stack.imgur.com/IkUY2.png)](https://i.stack.imgur.com/IkUY2.png)
26,268,743
This is only an iOS 8 problem, the keyboard displays correctly in iOS 7 with device orientation change. My application supports both portrait and landscape orientation and uses autolayout. If I push a UIViewController subclass that contains a UITextField subclass onto a navigation stack and the UITextField becomes the first responder in portrait orientation then the default keyboard displays correctly. However, if I rotate the device to landscape orientation then the UIViewController subview layouts are displayed correctly but the keyboard is displayed in the top center of the screen. The keyboard's orientation is correct for landscape orientation but it's frame width is the same width as expected for portrait orientation. If I set the app orientation to only landscape orientation then the keyboard does not display correctly. This is only a problem for iOS 8 orientation change.
2014/10/09
[ "https://Stackoverflow.com/questions/26268743", "https://Stackoverflow.com", "https://Stackoverflow.com/users/870964/" ]
Prior to iOS 8, the keyboard's location and width/height were always relative to portrait orientation when reported to the app. (e.g. Landscape's keyboard width is in the y direction, ~352 pixels on an iPad.) As of iOS 8, this has been updated to always have (0,0) at the top left of your (physical) view and the width/height reflect the x/y orientation you would normally expect outside of iOS. If you were previously positioning your keyboard via something like `keyboardDidShow`'s `[notification userInfo]`, you are going to get numbers that don't quite make sense. You can use something along these lines to take into account the pre-iOS8 idiosyncrasies: ``` - (void)keyboardDidShow: (NSNotification *) notification{ NSDictionary *keyboardInfo = [notification userInfo]; CGSize keyboardSize = [[keyboardInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size; UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation]; float height, width; if(UIInterfaceOrientationIsPortrait(orientation)){ width = keyboardSize.width; height = keyboardSize.height; } else { if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1){ width = keyboardSize.height; height = keyboardSize.width; } else { width = keyboardSize.width; height = keyboardSize.height; } } // Remainder of function } ``` Which can be refactored down to... ``` - (void)keyboardDidShow: (NSNotification *) notification{ NSDictionary *keyboardInfo = [notification userInfo]; CGSize keyboardSize = [[keyboardInfo objectForKey:UIKeyboardFrameBeginUserInfoKey] CGRectValue].size; UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation]; float width = keyboardSize.width; float height = keyboardSize.height; if(!UIInterfaceOrientationIsPortrait(orientation) && (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1)){ width = keyboardSize.height; height = keyboardSize.width; } // Remainder of function } ``` Also, the 8.1 update fixed several landscape/rotation bugs likely related to the above change. Grab the update and see if that solves your issue.
41,387,036
I've seen many Python algorithms that check for primality, but I have found that they all fail when checking a particular number: 28430288029929701389 I've used this algorithm: [What is the best algorithm for checking if a number is prime?](https://stackoverflow.com/questions/1801391/what-is-the-best-algorithm-for-checking-if-a-number-is-prime) ``` from __future__ import print_function import sys from sys import argv def is_prime(n): if n == 2: return True if n == 3: return True if n % 2 == 0: return False if n % 3 == 0: return False i = 5 w = 2 while i * i <= n: if n % i == 0: return False i += w w = 6 - w return True number_to_check = int(argv[1]) if is_prime(number_to_check): print("%d is prime" % number_to_check) else: print("%d is not prime" % number_to_check) ``` and these algorithms: <https://coderwall.com/p/utwriw/prime-numbers-with-python#comment_28424> and they all get into an endless loop when checking for primality of this particular number. I can check much bigger numbers and the result comes back instantly. Does anybody know if this is an issue with Python?
2016/12/29
[ "https://Stackoverflow.com/questions/41387036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6650713/" ]
Could it be because this number *is* a prime? Verifying takes `sqrt` time, and ``` In [10]: math.sqrt(28430288029929701389) Out[10]: 5332006004.303606 ``` Python is not a very fast language; looping 5332006004 times can take a *long* time. Much larger numbers you're trying can be composite, so a factor is found quickly. --- I'd recommend a probabilistic prime testing algorithm like [Miller-Rabin](https://en.wikipedia.org/wiki/Miller%E2%80%93Rabin_primality_test) or a variation thereof for "real-life" prime testing. These algorithms are drastically faster, and running them multiple times can bring the probability of error to lower than cosmic ray events easily.
5,285,844
Recompiling a C++ iPhone app with Xcode 4 I get this nasty linker error: ``` ld: bad codegen, pointer diff in __static_initialization_and_destruction_0(int, int) to global weak symbol vmml::Vector2<float>::ZERO for architecture armv6 ``` Anyone know what it means? How to make it go away would be nice too of course :) The app compiled & linked without error in Xcode 3. **Edit**: the solution is to set *Symbols Hidden By Default* to *Yes* in all the build settings of all targets in the project. Still none the wiser what the actual problem was.
2011/03/12
[ "https://Stackoverflow.com/questions/5285844", "https://Stackoverflow.com", "https://Stackoverflow.com/users/494373/" ]
The solution is to set `Symbols Hidden By Default` to *Yes* in all the build settings of all targets in the project. Still none the wiser what the actual problem was.