qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
769,854 |
I am executing `dir /q` on a Windows server 2008r2 and what I get back for one of the folders is `...` What does it mean?
```
2014-06-11 16:32 <KAT> ... AFolder
2014-06-03 16:17 <KAT> MyDomain\AUser AnotherFolder
```
My guess is that is somehow has to do with inheritance but can't find neither documentation nor a reason for this folder to have a different owner than any other.
|
2014/06/17
|
[
"https://superuser.com/questions/769854",
"https://superuser.com",
"https://superuser.com/users/129732/"
] |
A disk with bad sectors is not reliable. Modern disks have the capacity to transparently map out a handful of bad sectors -- as many as are deemed acceptable in terms of manufacturing defects, etc. When the number of bad sectors exceeds that value, it means that the disk is on its last legs. Although the disk *might* last a significant period of time without having the bad sectors spread, it's just as likely, if not more so, that new bad sectors will appear in the near future.
You say you plan to sell the disk to a friend of yours. If he's really your friend, you won't do so; instead, you'll wipe the disk of sensitive data and take it somewhere for recycling. At this point, it's really only safe as raw materials. (Of course, that leaves aside the question of the environmental and social impacts of "recycling" of electronics as it's often done today, but that's another matter.)
|
As far as I know what can be programmatically blocked, can later be programmatically unblocked provided user has enough technical knowledge and spare time.
Any software method you will use to block the corrupt area of the disk can later be overridden.
If you hide the partition using DiskPart, your friend can use DiskPart to unhide it
If you leave the space unpartitioned your friend can use Disk Management to create a volume.
Your best bet is to repartition the disk so that the area with bad sectors are left out as unpartitioned space and explicitely explain the situation to your friend to make sure he does not try to use it. It is only 20 GB after all.
|
769,854 |
I am executing `dir /q` on a Windows server 2008r2 and what I get back for one of the folders is `...` What does it mean?
```
2014-06-11 16:32 <KAT> ... AFolder
2014-06-03 16:17 <KAT> MyDomain\AUser AnotherFolder
```
My guess is that is somehow has to do with inheritance but can't find neither documentation nor a reason for this folder to have a different owner than any other.
|
2014/06/17
|
[
"https://superuser.com/questions/769854",
"https://superuser.com",
"https://superuser.com/users/129732/"
] |
You can indeed *hide* those sectors, but that won't prevent the disk to **continue failing**. You can create a new partition table, which effectively wipes all the information on the drive, and make a partition that **starts at 20GB** and goes up to the end of the disk, but **there's no way** to prevent your friend to create a new partition that starts at the very beginning of the drive and thus, discovering the bad sectors.
But anyway, if you insist; I suggest you use a proper tool, like [**GParted**](http://gparted.org/). Just burn the ISO to a disk (or make a bootable USB stick) and boot from it. It requires some knowledge about filesystems and partition tables, and [**how to operate this application**](http://gparted.org/display-doc.php?name=help-manual&). You'll find it easier with this tool since, as I mentioned, it's bootable so the drives are not in use while you perform changes on the partition layout.
|
As far as I know what can be programmatically blocked, can later be programmatically unblocked provided user has enough technical knowledge and spare time.
Any software method you will use to block the corrupt area of the disk can later be overridden.
If you hide the partition using DiskPart, your friend can use DiskPart to unhide it
If you leave the space unpartitioned your friend can use Disk Management to create a volume.
Your best bet is to repartition the disk so that the area with bad sectors are left out as unpartitioned space and explicitely explain the situation to your friend to make sure he does not try to use it. It is only 20 GB after all.
|
46,876,901 |
I just don't get it right. How do I center *list items* inside the `ul`?
```css
body {margin: 0}
ul {
width: 1000px;
margin: 0 auto;
padding: 0;
list-style-type: none;
margin-top: 30px;
overflow: hidden;
background-color: #333;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
ul li {
display: inline;
}
li a {
display: inline-block;
padding: 8px 11px;
margin-right: 10px;
color: #fff;
text-decoration: none;
text-align: center;
font-size: 18px;
line-height: 50px;
}
li a:hover {
background-color: #111;
}
```
```html
<ul>
<li><a href="#">Home</a><li>
<li><a href="#">Over mij</a><li>
<li><a href="#">PO's</a><li>
<li><a href="#">Contact</a><li>
</ul>
```
|
2017/10/22
|
[
"https://Stackoverflow.com/questions/46876901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5853817/"
] |
You can use the `location` prop to access the state you have passed. Visit [React-Router](https://reacttraining.com/react-router/web/api/location) for reference. When you want to access that state, you can do it by `this.props.location.state`.
|
you can access state using `this.props.location.state`
|
46,876,901 |
I just don't get it right. How do I center *list items* inside the `ul`?
```css
body {margin: 0}
ul {
width: 1000px;
margin: 0 auto;
padding: 0;
list-style-type: none;
margin-top: 30px;
overflow: hidden;
background-color: #333;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
ul li {
display: inline;
}
li a {
display: inline-block;
padding: 8px 11px;
margin-right: 10px;
color: #fff;
text-decoration: none;
text-align: center;
font-size: 18px;
line-height: 50px;
}
li a:hover {
background-color: #111;
}
```
```html
<ul>
<li><a href="#">Home</a><li>
<li><a href="#">Over mij</a><li>
<li><a href="#">PO's</a><li>
<li><a href="#">Contact</a><li>
</ul>
```
|
2017/10/22
|
[
"https://Stackoverflow.com/questions/46876901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5853817/"
] |
You can use the `location` prop to access the state you have passed. Visit [React-Router](https://reacttraining.com/react-router/web/api/location) for reference. When you want to access that state, you can do it by `this.props.location.state`.
|
If you're using React hooks you can use `useLocation` hook.
```
import { useLocation } from 'react-router-dom';
export const MyComponent = () => {
const { state } = useLocation();
...
}
```
|
46,876,901 |
I just don't get it right. How do I center *list items* inside the `ul`?
```css
body {margin: 0}
ul {
width: 1000px;
margin: 0 auto;
padding: 0;
list-style-type: none;
margin-top: 30px;
overflow: hidden;
background-color: #333;
font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
}
ul li {
display: inline;
}
li a {
display: inline-block;
padding: 8px 11px;
margin-right: 10px;
color: #fff;
text-decoration: none;
text-align: center;
font-size: 18px;
line-height: 50px;
}
li a:hover {
background-color: #111;
}
```
```html
<ul>
<li><a href="#">Home</a><li>
<li><a href="#">Over mij</a><li>
<li><a href="#">PO's</a><li>
<li><a href="#">Contact</a><li>
</ul>
```
|
2017/10/22
|
[
"https://Stackoverflow.com/questions/46876901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5853817/"
] |
If you're using React hooks you can use `useLocation` hook.
```
import { useLocation } from 'react-router-dom';
export const MyComponent = () => {
const { state } = useLocation();
...
}
```
|
you can access state using `this.props.location.state`
|
15,740,802 |
I want each JButton to also have a number or id associated with it. That is why I decided to extend the JButton class to make a class SuperJButton.
How do I include the value of the id/number in the action event generated when this button is clicked so that the class which responds to this action can access the id ?
|
2013/04/01
|
[
"https://Stackoverflow.com/questions/15740802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1667147/"
] |
Another alternative which doesn't require sub-classing, could be to use `JComponent.putClientProperty(Object key, Object value)` to store the ID associated with your button.
It can be retrieved using `getClientProperty(Object key)`.
```
public void actionPerformed(ActionEvent e)
{
JComponent comp = (JComponent)e.getSource();
KeyObject kObj = (KeyObject)comp.getClientProperty("button.id");
}
```
That might be a bit more flexible as you can attach this ID to every button without the need to use an application specific code e.g. when using a GUI builder where it's a bit complicated to change the creation code for a button, or when you need to use already existing components.
|
You don't have to change the Action event.You can do this,
```
SuperJButton jButton = (SuperJButton) actionEvent.getSource();
jButton.getId()
jButton.getNumber()
```
|
15,740,802 |
I want each JButton to also have a number or id associated with it. That is why I decided to extend the JButton class to make a class SuperJButton.
How do I include the value of the id/number in the action event generated when this button is clicked so that the class which responds to this action can access the id ?
|
2013/04/01
|
[
"https://Stackoverflow.com/questions/15740802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1667147/"
] |
You don't have to change the Action event.You can do this,
```
SuperJButton jButton = (SuperJButton) actionEvent.getSource();
jButton.getId()
jButton.getNumber()
```
|
From `MVC` point of view: `JButton` is a `view`, and `JButton` class is not better place to something like `id`. Much better place for an id is in your own `ButtonModel` implementation.
|
15,740,802 |
I want each JButton to also have a number or id associated with it. That is why I decided to extend the JButton class to make a class SuperJButton.
How do I include the value of the id/number in the action event generated when this button is clicked so that the class which responds to this action can access the id ?
|
2013/04/01
|
[
"https://Stackoverflow.com/questions/15740802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1667147/"
] |
Another alternative which doesn't require sub-classing, could be to use `JComponent.putClientProperty(Object key, Object value)` to store the ID associated with your button.
It can be retrieved using `getClientProperty(Object key)`.
```
public void actionPerformed(ActionEvent e)
{
JComponent comp = (JComponent)e.getSource();
KeyObject kObj = (KeyObject)comp.getClientProperty("button.id");
}
```
That might be a bit more flexible as you can attach this ID to every button without the need to use an application specific code e.g. when using a GUI builder where it's a bit complicated to change the creation code for a button, or when you need to use already existing components.
|
From `MVC` point of view: `JButton` is a `view`, and `JButton` class is not better place to something like `id`. Much better place for an id is in your own `ButtonModel` implementation.
|
225,691 |
Is it possible to separate the email hosting for my domain into a couple of different hosts?
For example `company.com` has emails going to Google (apps for business) and Microsoft Online Services (exchange). `Employee A's` inbox is at *Microsoft online services* as `[email protected]` while `Employee B's` inbox is at *Google* as `[email protected]`.
|
2011/01/23
|
[
"https://serverfault.com/questions/225691",
"https://serverfault.com",
"https://serverfault.com/users/7330/"
] |
This is possible, but not completely independently.
You need to have one primary mail provider which accepts all of your mail.
Then configure mailboxes there to forward emails to another account.
For example, set up company.com at Google, and a new domain, company.net at Microsoft.
Have Google forward all emails for [email protected], to [email protected].
Finally, set up the [email protected] account so it can send emails with the From address of "[email protected]".
The reason you have to do it this way, it the way email is routed around the internet.
Email routing is per-domain, with one or more mail servers listed in DNS as being responsible for email. However, in DNS you specify which of your mail servers has the highest priority, and which others should only be tried when the primary is unreachable.
Your secondary mail servers will then forward all mail received to the primary, which is responsible for putting email into a particular user's mailbox or forwarding it on to another address.
There is one alternative to this, if you're willing to run your own mail server:
You could conceivably run a mail server on your own network which accepts all of your email for company.com, and then routes mail for individual mailboxes to specific destinations (Google or Microsoft). However to the best of my knowledge, Google and Microsoft don't offer this solution for you so you'd have to run your own mail server to achieve it.
|
The most simple solution when using Google Apps (like in your case) is to enable dual delivery in Google Apps.
* More details here: <http://www.google.com/support/a/bin/answer.py?hl=en&answer=96855>
|
23,560,845 |
Is it possible to access beans defined outside of the step scope? For example, if I define a strategy "strategyA" and pass it in the job parameters I would like the @Value to resolve to the strategyA bean. Is this possible? I am currently working round the problem by getting the bean manually from the applicationContext.
```
@Bean
@StepScope
public Tasklet myTasklet(
@Value("#{jobParameters['strategy']}") MyCustomClass myCustomStrategy)
MyTasklet myTasklet= new yTasklet();
myTasklet.setStrategy(myCustomStrategy);
return myTasklet;
}
```
I would like to have the ability to add more strategies without having to modify the code.
|
2014/05/09
|
[
"https://Stackoverflow.com/questions/23560845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/318381/"
] |
The sort answer is yes. This is more general spring/design pattern issue rater then Spring Batch.
The Spring Batch tricky parts are the configuration and understanding scope of bean creation.
Let’s assume all your Strategies implement Strategy interface that looks like:
```
interface Strategy {
int execute(int a, int b);
};
```
Every strategy should implements Strategy and use @Component annotation to allow **automatic** discovery of new Strategy. Make sure all new strategy will placed under the correct package so component scan will find them.
For example:
```
@Component
public class StrategyA implements Strategy {
@Override
public int execute(int a, int b) {
return a+b;
}
}
```
The above are singletons and will be created on the application context initialization.
This stage is too early to use @Value("#{jobParameters['strategy']}") as JobParameter wasn't created yet.
So I suggest a locator bean that will be used later when myTasklet is created (Step Scope).
StrategyLocator class:
```
public class StrategyLocator {
private Map<String, ? extends Strategy> strategyMap;
public Strategy lookup(String strategy) {
return strategyMap.get(strategy);
}
public void setStrategyMap(Map<String, ? extends Strategy> strategyMap) {
this.strategyMap = strategyMap;
}
}
```
Configuration will look like:
```
@Bean
@StepScope
public MyTaskelt myTasklet () {
MyTaskelt myTasklet = new MyTaskelt();
//set the strategyLocator
myTasklet.setStrategyLocator(strategyLocator());
return myTasklet;
}
@Bean
protected StrategyLocator strategyLocator(){
return = new StrategyLocator();
}
```
To initialize StrategyLocator we need to make sure all strategy were already created. So the best approach would be to use ApplicationListener on ContextRefreshedEvent event (warning in this example strategy names start with lower case letter, changing this is easy...).
```
@Component
public class PlugableStrategyMapper implements ApplicationListener<ContextRefreshedEvent> {
@Autowired
private StrategyLocator strategyLocator;
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
Map<String, Strategy> beansOfTypeStrategy = applicationContext.getBeansOfType(Strategy.class);
strategyLocator.setStrategyMap(beansOfTypeStrategy);
}
}
```
The tasklet will hold a field of type String that will be injected with Strategy enum String using @Value and will be resolved using the locator using a "before step" Listener.
```
public class MyTaskelt implements Tasklet,StepExecutionListener {
@Value("#{jobParameters['strategy']}")
private String strategyName;
private Strategy strategy;
private StrategyLocator strategyLocator;
@BeforeStep
public void beforeStep(StepExecution stepExecution) {
strategy = strategyLocator.lookup(strategyName);
}
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
int executeStrategyResult = strategy.execute(1, 2);
}
public void setStrategyLocator(StrategyLocator strategyLocator) {
this.strategyLocator = strategyLocator;
}
}
```
To attach the listener to the taskelt you need to set it in your step configuration:
```
@Bean
protected Step myTaskletstep() throws MalformedURLException {
return steps.get("myTaskletstep")
.transactionManager(transactionManager())
.tasklet(deleteFileTaskelt())
.listener(deleteFileTaskelt())
.build();
}
```
|
`jobParameters` is holding just a String object and not the real object (and I think is not a good pratice store a bean definition into parameters).
I'll move in this way:
```
@Bean
@StepScope
class MyStategyHolder {
private MyCustomClass myStrategy;
// Add get/set
@BeforeJob
void beforeJob(JobExecution jobExecution) {
myStrategy = (Bind the right strategy using job parameter value);
}
}
```
and register `MyStategyHolder` as listener.
In your tasklet use `@Value("#{MyStategyHolder.myStrategy}")` or access `MyStategyHolder` instance and perform a `getMyStrategy()`.
|
59,437,973 |
An aspx page is loaded up inside a modal using Kendo Dialog for angular.
Intended behaviour for this page is once it is generated it opens the print dialogue. The output of that printing action should be the aspx page. It is so when printed from Chrome/Firefox but IE11 prints only a part of the page behind the actual modal dialogue.
This is achieved in aspx code as follows:
```
if (!(rsClinicList.EOF))
{
Response.Write("onLoad=\"doPrint();\"");
}
```
And method called is simply:
```
function doPrint() {
window.print();
}
```
So this works exactly as expected inside Chrome/Firefox, how to print the correct content using IE11?
|
2019/12/21
|
[
"https://Stackoverflow.com/questions/59437973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10056183/"
] |
The client credentials flow is described in the OAuth2 [RFC-6749](https://www.rfc-editor.org/rfc/rfc6749#section-4.4). The client id and secret are base64 encoded in a Basic authentication scheme as described in [RFC-7617](https://www.rfc-editor.org/rfc/rfc7617)
You should be able to get a token using Python code like:
```
import requests
import base64
url = 'https://ops.epo.org/3.2/auth/accesstoken'
data = {"grant_type": "client_credentials"}
creds = base64.b64encode("O220VlTQqAmodifiedsf0YeqgM6c:swWmodified3edjORU".encode())
headers = {'Authorization': 'Basic ' + creds.decode('UTF-8'), 'Content-Type': 'application/x-www-form-urlencoded'}
response = requests.post(url, headers=headers, data=data)
access_token = response.json()["access_token"]
```
|
When using the previous response I can obtain a token. (Thanks a lot for your answer)
So I tried :
```
myUrl = 'http://ops.epo.org/3.2/rest-services/register/publication/EPODOC/EP2814089/biblio'
header = {'PRIVATE-TOKEN': myToken}
response = requests.get(myUrl, headers=header)
print(response.text)
```
but I obtained a 403 error.
I finally got a specific library to do the job :
[EPO OPS Library](https://pypi.org/project/python-epo-ops-client)
But I still don't know how to do it on my own...
|
51,133,101 |
My question is simple is a UI/UX design question. I want to get this model for my layout [](https://i.stack.imgur.com/S0U73.jpg)
I have no idea how is this called, want some help and idea for coding this one I tried few options but nothing.
|
2018/07/02
|
[
"https://Stackoverflow.com/questions/51133101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9412929/"
] |
To create this above layout You can use either of FrameLayout or Co-ordinator Layout or the new ConstraintLayout.
This will do it for you.
[Refer this link to understand the above design.](https://github.com/hi-manshu/CryptoKoin/blob/master/app/src/main/res/layout/activity_main.xml)
```
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="xyz.himanshusingh.cryptokoin.ui.display.MainActivity">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="@drawable/toolbargradient" />
<FrameLayout
android:layout_width="match_parent"
android:layout_height="130dp"
android:layout_below="@+id/toolbar"
android:background="@drawable/toolbargradient" />
<android.support.v7.widget.CardView
android:id="@+id/cardView"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="80dp"
app:cardCornerRadius="10dp">
</android.support.v7.widget.CardView>
</RelativeLayout>
```
and toolbargradient.xml,
```
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:type="linear"
android:startColor="#f7792e"
android:endColor="#ef246b"
android:angle="180"/>
</shape>
```
This XML code will almost make the design for you. In place of CardView you can use whatever you want.Like a RecyclerView, DatePicker etc.
Hope this helps :)
|
Try using a Relative Layout for the image & recycler view and put the recycler view in cardview. This should work for 1st & 2nd view & in 3rd inside a cardview add a calendar & a recycler view below it. Hope this helps
|
29,192,219 |
How do I store the user input into the Insert VALUES of the two html form values?
In the last line of the script VALUES doesn't store these from form
```
<?php
error_reporting(0);
require 'connectit.php';
mysqli_query($db, "INSERT INTO bills (bill_name, bill_cost)
VALUES ($_POST['bill_name'], $_POST['bill_cost'])";
?>
// html form
<form action="updatebill.php" method="post">
<input type="text" name="bill_name" placeholder="Bill name"><br>
<input type="text" name="bill_cost" placeholder="Bill cost"><br>
<input type="submit" value="Submit">
</form>
```
|
2015/03/22
|
[
"https://Stackoverflow.com/questions/29192219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4609277/"
] |
I would suggest starting by breaking down the question into smaller pieces.
The question asks for a method to calculate an employees pay, so that seems like a reasonable place to start. The question gives you the name of the method and what parameters it should take:
>
> ...a method called pay that accepts two parameters: a real number for an employee's hourly wage and an integer for the number of hours the employee worked that day. The method should return how much money to pay the employee for this day.
>
>
>
So your method would look like this:
```
public double pay(double hourlyWage, int numberOfHours) {
//TODO: complete
}
```
Then start adding the logic into the method - start with the simple case of no overtime, then go back and add the overtime calculation.
Finally, note that the question says to include four calls to the pay method in the main method - so you dont actually need to prompt for input.
|
Answer with code is like this,
```
public class PayJava {
public static void main(String[] argv) {
PayJava test = new PayJava();
double pay = test.pay(5.2,5);
System.out.println("Pay 1= " + pay);
pay = test.pay(4.00, 11);
System.out.println("Pay 2= " + pay);
pay = test.pay(5.50, 6);
System.out.println("Pay 3= " + pay);
pay = test.pay(7.50, 14);
System.out.println("Pay 4= " + pay);
}
private double pay(double wage , int hours) {
double overtime= 1.5;
int otHrs = 0;
int regHrs = 0;
if(hours > 8 ) {
regHrs = 8;
otHrs = hours - regHrs;
overtime = (wage*1.5)*otHrs;
} else {
regHrs = hours;
overtime = 0;
}
wage = (wage*regHrs)+overtime;
return wage;
}
}
```
|
310,991 |
In my previous question [question](https://electronics.stackexchange.com/questions/310899/midi-out-thru-circuit-questions#310968) I learnt I have to use inductor beads, which is also according to the MIDI specs, see below
[](https://i.stack.imgur.com/s6WKi.jpg)
They state 1K@100MHz, but if I look e.g. on AliExpress for inductor beads, I only see stats like RH3.5 \* 6 \* 0.8, see [AliExpress](https://www.aliexpress.com/item/Line-bead-inductors-bead-mandrel-hole-RH3-5-6-0-8-yuan-Free-Shipping/32443960239.html?spm=2114.01010208.3.9.pEA3PT&ws_ab_test=searchweb0_0,searchweb201602_4_10152_10065_10151_10068_10136_10137_10060_10155_10062_437_10154_10056_10055_10054_10059_303_100031_10099_10103_10102_10096_10052_10053_10142_10107_10050_10051_5030013_10084_10083_10119_10080_10082_10081_10177_10110_519_10111_10112_10113_10114_10182_10078_10079_10073_10123_10120_10189_142,searchweb201603_16,ppcSwitch_4&btsid=7b3e9970-1e4a-4f83-87a2-b5665f0bfe20&algo_expid=65c0be0c-e215-4491-b871-86aeb873c442-1&algo_pvid=65c0be0c-e215-4491-b871-86aeb873c442).
How can I convert these specs?
(btw, I do not want SMD, I use DIP/normal breadboard style components).
Update:
I found probably something better: R6T 2,5T (or 3T) [R6](https://www.aliexpress.com/item/Free-shipping-50PCS-3T-6-10-Six-hole-Magnetic-bead-3-Coil-R6H-anti-interference-inductance/32817155597.html?spm=2114.01010208.3.23.7RlqB0&ws_ab_test=searchweb0_0,searchweb201602_4_10152_10065_10151_10068_10136_10137_10060_10155_10062_437_10154_10056_10055_10054_10059_303_100031_10099_10103_10102_10096_10052_10053_10142_10107_10050_10051_5030013_10084_10083_10119_10080_10082_10081_10177_10110_519_10111_10112_10113_10114_10182_10078_10079_10073_10123_10120_10189_142-10120,searchweb201603_50,ppcSwitch_4&btsid=9acaa97e-3bab-482b-85ff-086a168eedba&algo_expid=e560cf68-93d2-4e80-937f-54ae743fef9d-3&algo_pvid=e560cf68-93d2-4e80-937f-54ae743fef9d)
These are according to a similar looking [spec](http://www.meisongbei.com/ferrite_beads/2009-12-24/4874.chtml) 600 or 800 ohm (of course if the components are similar, but it seems better than RH3.5's).
|
2017/06/14
|
[
"https://electronics.stackexchange.com/questions/310991",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/140343/"
] |
Apart from the fact that a coil across the emitter resistor completely alters the dc quiescent point of your transistor you have to think about what the input impedance is looking into the emitter.
You are driving a current through the collector that is quite high because the base bias is a single pull up resistor. With maybe 3 mA flowing in the collector, the input impedance to the emitter is about 9 ohms. This is largely dictated by the formula 26 mV / Ic.
So, if you put 9 ohms across the coil and looked at the signal on the oscilloscope you can't expect your signal to be unaffected. It's going to be highly attenuated.
So, two things, ones a problem and one is an issue. Try feeding the coil to the base and design a properly biased common emitter circuit. You should be able to get a gain of thirty.
Better still, resonate your coil with a tuning capacitor and you might get ten times more signal.
|
This is not a useful circuit:
[](https://i.stack.imgur.com/lvmFp.gif)
1. A coil connected across R3 will mess up the DC bias point by shorting the emitter to ground.
- Even if the coil were AC coupled, the bias point is indeterminate since it depends highly on the gain of Q1.
With proper biasing and AC coupling, a common base amplifier could be useful since the input signal has such low impedance.
|
38,655,215 |
I'm trying to execute a `SQL` query using a Java `PreparedStatement` in Java 7 using the code below:
```
PreparedStatement functionalCRsStatement = con.prepareStatement(
"select * from openquery(SERVER,\n" +
"\t'Select X , Y, Z, A from D r\n" +
"\tINNER JOIN E c\n" +
"\tON r.RNID = c.RNID\n" +
"\twhere c.Y = ?')\n");
functionalCRsStatement.setString(2, x);
```
I get the following error message: `com.microsoft.sqlserver.jdbc.SQLServerException: The index 2 is out of range.`
PS: I'm sure of the correctness of the SQL query because I successfully tested it without a `PreparedStatement`, I just replaced the real name of the columns in the query by fake ones (X, Y, Z) to hide potentially confidential information.
**EDIT**: I get a similar error when using `setString(1, x)` => `index 1 is out of range`
|
2016/07/29
|
[
"https://Stackoverflow.com/questions/38655215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6556658/"
] |
It seems you only have one `?` in your statement, so you can't make a reference to the second index (2) in the `functionalCRsStatement.setString(2, x);`, because as it says, it's out of range.
you should use
```
functionalCRsStatement.setString(1, x);
```
|
You have only one parameter to set in your prepared statement. the set method to set parameter in prepared statement checks index of the `?` in the prepared statement and sets the value to prepared statement accordingly.
So in your case there is only 1 `?` so in an array of values to be passed for prepared statement is 1. and you are trying to pass the value at the index 2 hence it says The
>
> index 2 is out of range.
>
>
>
Try the same with index 1. as you have only 1 parameter to be set.
e.g. **functionalCRsStatement.setString(1, x);**
remember the value x will be stored to the `?` at 1st index in the prepared statement.
**EDIT** : Also remember the type to the value to be passed. if you are setting value of X as int you need to call setInt(1,x). in this case it will not able to find first index os String and throw an error of index out of range.
|
38,655,215 |
I'm trying to execute a `SQL` query using a Java `PreparedStatement` in Java 7 using the code below:
```
PreparedStatement functionalCRsStatement = con.prepareStatement(
"select * from openquery(SERVER,\n" +
"\t'Select X , Y, Z, A from D r\n" +
"\tINNER JOIN E c\n" +
"\tON r.RNID = c.RNID\n" +
"\twhere c.Y = ?')\n");
functionalCRsStatement.setString(2, x);
```
I get the following error message: `com.microsoft.sqlserver.jdbc.SQLServerException: The index 2 is out of range.`
PS: I'm sure of the correctness of the SQL query because I successfully tested it without a `PreparedStatement`, I just replaced the real name of the columns in the query by fake ones (X, Y, Z) to hide potentially confidential information.
**EDIT**: I get a similar error when using `setString(1, x)` => `index 1 is out of range`
|
2016/07/29
|
[
"https://Stackoverflow.com/questions/38655215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6556658/"
] |
It seems you only have one `?` in your statement, so you can't make a reference to the second index (2) in the `functionalCRsStatement.setString(2, x);`, because as it says, it's out of range.
you should use
```
functionalCRsStatement.setString(1, x);
```
|
The prepared statement is not recognizing any param, for is this query contains 0 params because of mal-written string; try this :
```
PreparedStatement functionalCRsStatement = con.prepareStatement(
"select * from openquery(APRPRD," +
"'Select X , Y, Z, A from D r" +
"INNER JOIN E c" +
"ON r.RNID = c.RNID ')" +
"where c.Y = ?");
```
|
38,655,215 |
I'm trying to execute a `SQL` query using a Java `PreparedStatement` in Java 7 using the code below:
```
PreparedStatement functionalCRsStatement = con.prepareStatement(
"select * from openquery(SERVER,\n" +
"\t'Select X , Y, Z, A from D r\n" +
"\tINNER JOIN E c\n" +
"\tON r.RNID = c.RNID\n" +
"\twhere c.Y = ?')\n");
functionalCRsStatement.setString(2, x);
```
I get the following error message: `com.microsoft.sqlserver.jdbc.SQLServerException: The index 2 is out of range.`
PS: I'm sure of the correctness of the SQL query because I successfully tested it without a `PreparedStatement`, I just replaced the real name of the columns in the query by fake ones (X, Y, Z) to hide potentially confidential information.
**EDIT**: I get a similar error when using `setString(1, x)` => `index 1 is out of range`
|
2016/07/29
|
[
"https://Stackoverflow.com/questions/38655215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6556658/"
] |
As @JonK commented, you have apostrophes in your query, which means your parameter is actually inside a string where the SQL engine won't bind a value (whether you use 1 or 2 as the index):
```
PreparedStatement functionalCRsStatement = con.prepareStatement(
"select * from openquery(APRPRD,\n" +
"\t'Select X , Y, Z, A from D r\n" +
"\tINNER JOIN E c\n" +
"\tON r.RNID = c.RNID\n" +
"\twhere c.Y = ?')\n");
```
contains this query (with SQL syntax highlighting, which shows the whole string)
```
select * from openquery(APRPRD,
'Select X , Y, Z, A from D r
INNER JOIN E c
ON r.RNID = c.RNID
where c.Y = ?')
```
A SQL engine never inspects the inside of a string. How would you insert a string containing a question mark otherwise?
|
It seems you only have one `?` in your statement, so you can't make a reference to the second index (2) in the `functionalCRsStatement.setString(2, x);`, because as it says, it's out of range.
you should use
```
functionalCRsStatement.setString(1, x);
```
|
38,655,215 |
I'm trying to execute a `SQL` query using a Java `PreparedStatement` in Java 7 using the code below:
```
PreparedStatement functionalCRsStatement = con.prepareStatement(
"select * from openquery(SERVER,\n" +
"\t'Select X , Y, Z, A from D r\n" +
"\tINNER JOIN E c\n" +
"\tON r.RNID = c.RNID\n" +
"\twhere c.Y = ?')\n");
functionalCRsStatement.setString(2, x);
```
I get the following error message: `com.microsoft.sqlserver.jdbc.SQLServerException: The index 2 is out of range.`
PS: I'm sure of the correctness of the SQL query because I successfully tested it without a `PreparedStatement`, I just replaced the real name of the columns in the query by fake ones (X, Y, Z) to hide potentially confidential information.
**EDIT**: I get a similar error when using `setString(1, x)` => `index 1 is out of range`
|
2016/07/29
|
[
"https://Stackoverflow.com/questions/38655215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6556658/"
] |
You have only one bind variable placeholder (`?`) in your query - so you should bind it with an index of `1`, not `2`:
```
functionalCRsStatement.setString(1, x); // Was 2 in the OP
```
|
You have only one parameter to set in your prepared statement. the set method to set parameter in prepared statement checks index of the `?` in the prepared statement and sets the value to prepared statement accordingly.
So in your case there is only 1 `?` so in an array of values to be passed for prepared statement is 1. and you are trying to pass the value at the index 2 hence it says The
>
> index 2 is out of range.
>
>
>
Try the same with index 1. as you have only 1 parameter to be set.
e.g. **functionalCRsStatement.setString(1, x);**
remember the value x will be stored to the `?` at 1st index in the prepared statement.
**EDIT** : Also remember the type to the value to be passed. if you are setting value of X as int you need to call setInt(1,x). in this case it will not able to find first index os String and throw an error of index out of range.
|
38,655,215 |
I'm trying to execute a `SQL` query using a Java `PreparedStatement` in Java 7 using the code below:
```
PreparedStatement functionalCRsStatement = con.prepareStatement(
"select * from openquery(SERVER,\n" +
"\t'Select X , Y, Z, A from D r\n" +
"\tINNER JOIN E c\n" +
"\tON r.RNID = c.RNID\n" +
"\twhere c.Y = ?')\n");
functionalCRsStatement.setString(2, x);
```
I get the following error message: `com.microsoft.sqlserver.jdbc.SQLServerException: The index 2 is out of range.`
PS: I'm sure of the correctness of the SQL query because I successfully tested it without a `PreparedStatement`, I just replaced the real name of the columns in the query by fake ones (X, Y, Z) to hide potentially confidential information.
**EDIT**: I get a similar error when using `setString(1, x)` => `index 1 is out of range`
|
2016/07/29
|
[
"https://Stackoverflow.com/questions/38655215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6556658/"
] |
You have only one bind variable placeholder (`?`) in your query - so you should bind it with an index of `1`, not `2`:
```
functionalCRsStatement.setString(1, x); // Was 2 in the OP
```
|
The prepared statement is not recognizing any param, for is this query contains 0 params because of mal-written string; try this :
```
PreparedStatement functionalCRsStatement = con.prepareStatement(
"select * from openquery(APRPRD," +
"'Select X , Y, Z, A from D r" +
"INNER JOIN E c" +
"ON r.RNID = c.RNID ')" +
"where c.Y = ?");
```
|
38,655,215 |
I'm trying to execute a `SQL` query using a Java `PreparedStatement` in Java 7 using the code below:
```
PreparedStatement functionalCRsStatement = con.prepareStatement(
"select * from openquery(SERVER,\n" +
"\t'Select X , Y, Z, A from D r\n" +
"\tINNER JOIN E c\n" +
"\tON r.RNID = c.RNID\n" +
"\twhere c.Y = ?')\n");
functionalCRsStatement.setString(2, x);
```
I get the following error message: `com.microsoft.sqlserver.jdbc.SQLServerException: The index 2 is out of range.`
PS: I'm sure of the correctness of the SQL query because I successfully tested it without a `PreparedStatement`, I just replaced the real name of the columns in the query by fake ones (X, Y, Z) to hide potentially confidential information.
**EDIT**: I get a similar error when using `setString(1, x)` => `index 1 is out of range`
|
2016/07/29
|
[
"https://Stackoverflow.com/questions/38655215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6556658/"
] |
As @JonK commented, you have apostrophes in your query, which means your parameter is actually inside a string where the SQL engine won't bind a value (whether you use 1 or 2 as the index):
```
PreparedStatement functionalCRsStatement = con.prepareStatement(
"select * from openquery(APRPRD,\n" +
"\t'Select X , Y, Z, A from D r\n" +
"\tINNER JOIN E c\n" +
"\tON r.RNID = c.RNID\n" +
"\twhere c.Y = ?')\n");
```
contains this query (with SQL syntax highlighting, which shows the whole string)
```
select * from openquery(APRPRD,
'Select X , Y, Z, A from D r
INNER JOIN E c
ON r.RNID = c.RNID
where c.Y = ?')
```
A SQL engine never inspects the inside of a string. How would you insert a string containing a question mark otherwise?
|
You have only one bind variable placeholder (`?`) in your query - so you should bind it with an index of `1`, not `2`:
```
functionalCRsStatement.setString(1, x); // Was 2 in the OP
```
|
38,655,215 |
I'm trying to execute a `SQL` query using a Java `PreparedStatement` in Java 7 using the code below:
```
PreparedStatement functionalCRsStatement = con.prepareStatement(
"select * from openquery(SERVER,\n" +
"\t'Select X , Y, Z, A from D r\n" +
"\tINNER JOIN E c\n" +
"\tON r.RNID = c.RNID\n" +
"\twhere c.Y = ?')\n");
functionalCRsStatement.setString(2, x);
```
I get the following error message: `com.microsoft.sqlserver.jdbc.SQLServerException: The index 2 is out of range.`
PS: I'm sure of the correctness of the SQL query because I successfully tested it without a `PreparedStatement`, I just replaced the real name of the columns in the query by fake ones (X, Y, Z) to hide potentially confidential information.
**EDIT**: I get a similar error when using `setString(1, x)` => `index 1 is out of range`
|
2016/07/29
|
[
"https://Stackoverflow.com/questions/38655215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6556658/"
] |
As @JonK commented, you have apostrophes in your query, which means your parameter is actually inside a string where the SQL engine won't bind a value (whether you use 1 or 2 as the index):
```
PreparedStatement functionalCRsStatement = con.prepareStatement(
"select * from openquery(APRPRD,\n" +
"\t'Select X , Y, Z, A from D r\n" +
"\tINNER JOIN E c\n" +
"\tON r.RNID = c.RNID\n" +
"\twhere c.Y = ?')\n");
```
contains this query (with SQL syntax highlighting, which shows the whole string)
```
select * from openquery(APRPRD,
'Select X , Y, Z, A from D r
INNER JOIN E c
ON r.RNID = c.RNID
where c.Y = ?')
```
A SQL engine never inspects the inside of a string. How would you insert a string containing a question mark otherwise?
|
You have only one parameter to set in your prepared statement. the set method to set parameter in prepared statement checks index of the `?` in the prepared statement and sets the value to prepared statement accordingly.
So in your case there is only 1 `?` so in an array of values to be passed for prepared statement is 1. and you are trying to pass the value at the index 2 hence it says The
>
> index 2 is out of range.
>
>
>
Try the same with index 1. as you have only 1 parameter to be set.
e.g. **functionalCRsStatement.setString(1, x);**
remember the value x will be stored to the `?` at 1st index in the prepared statement.
**EDIT** : Also remember the type to the value to be passed. if you are setting value of X as int you need to call setInt(1,x). in this case it will not able to find first index os String and throw an error of index out of range.
|
38,655,215 |
I'm trying to execute a `SQL` query using a Java `PreparedStatement` in Java 7 using the code below:
```
PreparedStatement functionalCRsStatement = con.prepareStatement(
"select * from openquery(SERVER,\n" +
"\t'Select X , Y, Z, A from D r\n" +
"\tINNER JOIN E c\n" +
"\tON r.RNID = c.RNID\n" +
"\twhere c.Y = ?')\n");
functionalCRsStatement.setString(2, x);
```
I get the following error message: `com.microsoft.sqlserver.jdbc.SQLServerException: The index 2 is out of range.`
PS: I'm sure of the correctness of the SQL query because I successfully tested it without a `PreparedStatement`, I just replaced the real name of the columns in the query by fake ones (X, Y, Z) to hide potentially confidential information.
**EDIT**: I get a similar error when using `setString(1, x)` => `index 1 is out of range`
|
2016/07/29
|
[
"https://Stackoverflow.com/questions/38655215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6556658/"
] |
As @JonK commented, you have apostrophes in your query, which means your parameter is actually inside a string where the SQL engine won't bind a value (whether you use 1 or 2 as the index):
```
PreparedStatement functionalCRsStatement = con.prepareStatement(
"select * from openquery(APRPRD,\n" +
"\t'Select X , Y, Z, A from D r\n" +
"\tINNER JOIN E c\n" +
"\tON r.RNID = c.RNID\n" +
"\twhere c.Y = ?')\n");
```
contains this query (with SQL syntax highlighting, which shows the whole string)
```
select * from openquery(APRPRD,
'Select X , Y, Z, A from D r
INNER JOIN E c
ON r.RNID = c.RNID
where c.Y = ?')
```
A SQL engine never inspects the inside of a string. How would you insert a string containing a question mark otherwise?
|
The prepared statement is not recognizing any param, for is this query contains 0 params because of mal-written string; try this :
```
PreparedStatement functionalCRsStatement = con.prepareStatement(
"select * from openquery(APRPRD," +
"'Select X , Y, Z, A from D r" +
"INNER JOIN E c" +
"ON r.RNID = c.RNID ')" +
"where c.Y = ?");
```
|
5,970,491 |
Here is my case:
I have a MongoDB collection in Node.Js.
Let's say three elements: **a, b, c** I want to insert new element as the first one and want the last one to go out.
So it would be:
**d, a, b**
In next iteration:
**e, d, a**
1.How to do that kind of insetion?
2.Is there a chance to listen for those insetions from another node.js app? Something like
```
collection.on('update', function() {
console.log('updated');
});
```
|
2011/05/11
|
[
"https://Stackoverflow.com/questions/5970491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/591939/"
] |
1. [Capped collections](http://www.mongodb.org/display/DOCS/Capped+Collections) in MongoDB preserve insertion order and discard the oldest items based on the total collection size (unfortunately measured in bytes). Seems like ideal fit for your scenario.
2. I believe there is no trigger/notification mechanism in MongoDB yet, only manual polling.
|
Another way to handle this would be to write a custom Queue object that would dequeue the last item when a new item was enqueued if the total number of items in the queue exceeded your requirements, and emit an 'item added' event that other parts of your application could listen for.
Here's some generic example code in which you would replace refs to Array, length, shift() and unshift() with calls to MongoDB:
```
var util=require('util'), // for inheritance
EventEmitter=require('events').EventEmitter, // for event handling
MaxQueueItems=10; // default total items in queue
var FixedSizeQueue=function(max){
this._storage=[]; // replace with call to MongoDB
this._max_items=max||MaxQueueItems;
};
util.inherits(FixedSizeQueue,EventEmitter); // now I can emit
FixedSizeQueue.prototype._add=function(item){ // private
// replace with call to MongoDB
this.emit('onItemAdd', this._storage.unshift(item), item);
};
FixedSizeQueue.prototype._remove=function(){ // private
// replace with call to MongoDB
var item=this._storage.shift();
if(item) {
this.emit('onItemRemove', this._storage.length, item);
return item;
}
};
FixedSizeQueue.prototype.enqueue=function(item){
if (this._storage.length+1 > this._max_items) {
this._remove();
}
this._add(item);
return(this); // for chaining
};
FixedSizeQueue.prototype.dequeue=function(){
return this._remove();
};
```
which could be used as:
```
var q=new FixedSizeQueue(3); // a queue with only three items
q.on('onItemAdd',function(len,item){
console.log('item added, queue now contains '+len+' items.');
});
q.on('onItemRemove',function(len,item){
console.log('item removed, queue now contains '+len+' items.');
});
q.enqueue(1); // emits onItemAdd, queue = (1)
q.enqueue(2); // emits onItemAdd, queue = (2,1)
q.enqueue(3); // emits onItemAdd, queue = (3,2,1)
q.enqueue(1); // emits onItemRemove and onItemAdd, queue = (4,3,2)
```
console output:
```
item added, queue now contains 1 items.
item added, queue now contains 2 items.
item added, queue now contains 3 items.
item removed, queue now contains 2 items.
item added, queue now contains 3 items.
```
|
38,659,717 |
I have the following code. Is there a better way to write it. It feels like when conditions and promises and querying from multiple tables are involved, the code becomes harder to read. Any help would be appreciated. Thanks!
```
fetchUserById = function (id) {
var user = {};
return knex_instance('user_info')
.where('id', id)
.first()
.then(function (data) {
if (!data) {
return null;
} else {
user.info = data;
return knex_instance('user_table')
.where('id', id)
.first()
.then(function (values) {
user.values = values;
return user;
});
}
})
.catch(errorHandler('fetchUserById', id));
}
```
|
2016/07/29
|
[
"https://Stackoverflow.com/questions/38659717",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/123132/"
] |
A `ScrollPane` stores its single child in the [`contentProperty`](https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/ScrollPane.html#contentProperty):
>
> The node used as the content of this ScrollPane.
>
>
>
Therefore corrected code is:
```
scrollPaneIdFx.setContent(imageViewIdFx);
```
In case of you would like to store multiple `Node`s in a `ScrollPane` the `contentProperty` should be set to one of the containers (`Parent` object) then the `Node`s should be added to this container.
|
There is only a single "child" you should add to a `ScrollPane`: the [`content`](https://docs.oracle.com/javase/8/javafx/api/javafx/scene/control/ScrollPane.html#contentProperty). If you want a `ScrollPane` that contains multiple `Node`s, add them to a suitable `Parent` (e.g. a `Pane`) and use this `Parent` as content of the `ScrollPane`.
Example
```
VBox content = new VBox();
content.getChildren().add(child1);
content.getChildren().add(child2);
...
scrollPane.setContent(content);
```
|
70,188 |
Most books I find on German grammar are precriptive in the sense that they try to describe Grammar by giving some rules. This approaches make the amount of thinking required the language less , but, I personally am also interested in the descriptive way which tries to form a general theory on what constitutes a meaningful German sentence.
Could some recommendation for reading be given?
|
2022/04/04
|
[
"https://german.stackexchange.com/questions/70188",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/51342/"
] |
The ultimate descriptive grammar of German (in English) may be Peter Jørgensen's *German Grammar*, translated by G. Kolisko and published by Heinemann in the years 1959-1966. This is now out of print, so you may need to go to a nearby university library, e.g. those included in WorldCat: [Volume 1](https://www.worldcat.org/title/german-grammar-vol-1/oclc/884736367), [Volume 2](https://www.worldcat.org/title/german-grammar-2-german-grammar-iii/oclc/490758233), [Volume 3](https://www.worldcat.org/title/german-grammar-3/oclc/614655715). You can find [volume 2 on Archive.org](https://archive.org/details/germangrammariin013552mbp).
If Jørgensen is too detailed for your taste, here are a few alternatives:
* [*German: An Essential Grammar*](https://www.routledge.com/German-An-Essential-Grammar/Donaldson/p/book/9780415366021) by Bruce Donaldson (Routledge, 2006). At 288 pages, this is rather brief, but the publisher describes it as "presenting a fresh and accessible *description* of the language" (emphasis mine).
* [*A Student Grammar of German*](https://www.cambridge.org/de/academic/subjects/languages-linguistics/european-language-and-linguistics/student-grammar-german?format=PB) by Paul Stocker (Cambridge University Press, 276 pages). Even though this book actually contains "rules", it also notes differences between written and spoken German, and variations found in German-speaking countries such as Switzerland and Austria.
* [*The Structure of German*](https://global.oup.com/academic/product/the-structure-of-german-9780199273997) by Anthony Fox (second edition, Oxford University Press, 2005). A description of the German language in linguistic terms. (At 348 pages, this is still fairly compact for a descriptive grammar.)
* [*The Syntax of German*](https://www.cambridge.org/de/academic/subjects/languages-linguistics/grammar-and-syntax/syntax-german?format=HB) by Hubert Haider (Cambridge University Press, 2010). This book is included because the question asked about the construction of German sentences. This book is squarely aimed at linguists who are familiar with terms such as VO, OV, morphosyntactics and infinitival constructions.
In German, the most detailed "recent" grammar is probably [*Grammatik der deutschen Sprache*](https://www.degruyter.com/document/doi/10.1515/9783110872163/html), in three volumes, by Gisela Zifonun, Ludger Hoffmann and Bruno Strecker (De Gruyter, 1997; over 2570 pages).
The reference I use is [*Duden – Die Grammatik*](https://shop.duden.de/products/die-grammatik), which is descriptive and regularly updated. (The ninth edition, published in 2016, has 1344 pages.)
Somewhat older, but still interesting, is Harald Weinrich's *Textgrammatik der deutsche Sprache* (first edition, 1993) because it uses the unit of the "text" as a starting point, whereas other descriptive grammars tend to begin with phonetics and then go over the diverse parts of speech and rarely discuss text-level grammar.
|
You might try: "Deskriptive Linguistik. Grundlagen und Methoden" by Michael Dürr and Peter Schlobinski; Vandenhoeck & Ruprecht, Göttingen, 2006, ISBN: 978-3525265185
|
70,188 |
Most books I find on German grammar are precriptive in the sense that they try to describe Grammar by giving some rules. This approaches make the amount of thinking required the language less , but, I personally am also interested in the descriptive way which tries to form a general theory on what constitutes a meaningful German sentence.
Could some recommendation for reading be given?
|
2022/04/04
|
[
"https://german.stackexchange.com/questions/70188",
"https://german.stackexchange.com",
"https://german.stackexchange.com/users/51342/"
] |
The ultimate descriptive grammar of German (in English) may be Peter Jørgensen's *German Grammar*, translated by G. Kolisko and published by Heinemann in the years 1959-1966. This is now out of print, so you may need to go to a nearby university library, e.g. those included in WorldCat: [Volume 1](https://www.worldcat.org/title/german-grammar-vol-1/oclc/884736367), [Volume 2](https://www.worldcat.org/title/german-grammar-2-german-grammar-iii/oclc/490758233), [Volume 3](https://www.worldcat.org/title/german-grammar-3/oclc/614655715). You can find [volume 2 on Archive.org](https://archive.org/details/germangrammariin013552mbp).
If Jørgensen is too detailed for your taste, here are a few alternatives:
* [*German: An Essential Grammar*](https://www.routledge.com/German-An-Essential-Grammar/Donaldson/p/book/9780415366021) by Bruce Donaldson (Routledge, 2006). At 288 pages, this is rather brief, but the publisher describes it as "presenting a fresh and accessible *description* of the language" (emphasis mine).
* [*A Student Grammar of German*](https://www.cambridge.org/de/academic/subjects/languages-linguistics/european-language-and-linguistics/student-grammar-german?format=PB) by Paul Stocker (Cambridge University Press, 276 pages). Even though this book actually contains "rules", it also notes differences between written and spoken German, and variations found in German-speaking countries such as Switzerland and Austria.
* [*The Structure of German*](https://global.oup.com/academic/product/the-structure-of-german-9780199273997) by Anthony Fox (second edition, Oxford University Press, 2005). A description of the German language in linguistic terms. (At 348 pages, this is still fairly compact for a descriptive grammar.)
* [*The Syntax of German*](https://www.cambridge.org/de/academic/subjects/languages-linguistics/grammar-and-syntax/syntax-german?format=HB) by Hubert Haider (Cambridge University Press, 2010). This book is included because the question asked about the construction of German sentences. This book is squarely aimed at linguists who are familiar with terms such as VO, OV, morphosyntactics and infinitival constructions.
In German, the most detailed "recent" grammar is probably [*Grammatik der deutschen Sprache*](https://www.degruyter.com/document/doi/10.1515/9783110872163/html), in three volumes, by Gisela Zifonun, Ludger Hoffmann and Bruno Strecker (De Gruyter, 1997; over 2570 pages).
The reference I use is [*Duden – Die Grammatik*](https://shop.duden.de/products/die-grammatik), which is descriptive and regularly updated. (The ninth edition, published in 2016, has 1344 pages.)
Somewhat older, but still interesting, is Harald Weinrich's *Textgrammatik der deutsche Sprache* (first edition, 1993) because it uses the unit of the "text" as a starting point, whereas other descriptive grammars tend to begin with phonetics and then go over the diverse parts of speech and rarely discuss text-level grammar.
|
It is not heavily theoretical, but Helbig/Buscha: "Deutsche Grammatik: ein Handbuch für den Ausländerunterricht" (Klett) is very descriptive. Many examples and exceptions are listed. It's German, though.
|
96,883 |
Humans have finally developed a shield completely made out of handwavium. Hurrah! This shield is unbreakable except to anti-tank rounds, RPGS, and other heavy weapons. Assuming the army could afford giving half of their troops handwavium shields, how would this change how modern (2017) infantry moves and takes cover? Assume the shield weighs about 40 pounds and have the same dimensions as a tower shield.
|
2017/11/03
|
[
"https://worldbuilding.stackexchange.com/questions/96883",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/44220/"
] |
I think it would not change much in modern warfare, as the current trend is less based on infantry combat. They would improve the existent uses of shields in military and police activity, but not change the tactics, as most tactics involve long distance, high-tech (drones), or explosive power. So it would just be used in the same scenarios shields are already used.
The material on the other hand could be used for many different things. Even if you can't forge precise forms you can enhance vehicle plating, body armour in smaller pieces to stop bullets.
But except for guerilla fights tower shields will not have an impact. And there it is only changing effectiveness and not tactics. (Modern shields are already almost impenetrable, after all)
|
Everything old becomes new again.
Your invention would bring back the use of mustard gas and other airborne poisons on the battlefield.
|
96,883 |
Humans have finally developed a shield completely made out of handwavium. Hurrah! This shield is unbreakable except to anti-tank rounds, RPGS, and other heavy weapons. Assuming the army could afford giving half of their troops handwavium shields, how would this change how modern (2017) infantry moves and takes cover? Assume the shield weighs about 40 pounds and have the same dimensions as a tower shield.
|
2017/11/03
|
[
"https://worldbuilding.stackexchange.com/questions/96883",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/44220/"
] |
The military doesn't supply everyone with the new hotness shield because some infantry will be slowed down by it. In WW2 soldier packs were supposedly already 90lbs. Do you seriously think that an infantryman wants to carry another 40lbs of cover with them at all times? That's 130lbs.. Weight is heavy.
Right now the units who do use shields in general are swat and riot people. Swat and riot people will get safer, however even they won't all switch to these 40lbs shields because it would make things more dangerous for the people their fighting. Imagine how hard it will be to not hurt rioting civilians if you have to move a 40lbs shield in a shield wall? SWAT doesn't even always use shields anyway. At the end of the day this will become a nice tool that the military has, but it won't be made standard.
Now if you put this in a vest on the other hand it would be used, but the tactics used with it would remain the same as tactics already used with heavy vests today.
|
If such shields were adopted, the result would simply be wider usage of mortars and automatic grenade launchers. Mortar bombs can explode behind or above a warfighter as well as before him, thus negating the shield. Grenades just plain destroy the shield and kill its user.
|
96,883 |
Humans have finally developed a shield completely made out of handwavium. Hurrah! This shield is unbreakable except to anti-tank rounds, RPGS, and other heavy weapons. Assuming the army could afford giving half of their troops handwavium shields, how would this change how modern (2017) infantry moves and takes cover? Assume the shield weighs about 40 pounds and have the same dimensions as a tower shield.
|
2017/11/03
|
[
"https://worldbuilding.stackexchange.com/questions/96883",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/44220/"
] |
I think it would not change much in modern warfare, as the current trend is less based on infantry combat. They would improve the existent uses of shields in military and police activity, but not change the tactics, as most tactics involve long distance, high-tech (drones), or explosive power. So it would just be used in the same scenarios shields are already used.
The material on the other hand could be used for many different things. Even if you can't forge precise forms you can enhance vehicle plating, body armour in smaller pieces to stop bullets.
But except for guerilla fights tower shields will not have an impact. And there it is only changing effectiveness and not tactics. (Modern shields are already almost impenetrable, after all)
|
The weapons you describe as being effective against the shields all have a large energetic yield. Then an obvious trend would be to develop weapons that deliver the same kind of impact but are smaller, cheaper and less messy on the battlefield.
Super-sniper rifles might be the order of the day.
|
96,883 |
Humans have finally developed a shield completely made out of handwavium. Hurrah! This shield is unbreakable except to anti-tank rounds, RPGS, and other heavy weapons. Assuming the army could afford giving half of their troops handwavium shields, how would this change how modern (2017) infantry moves and takes cover? Assume the shield weighs about 40 pounds and have the same dimensions as a tower shield.
|
2017/11/03
|
[
"https://worldbuilding.stackexchange.com/questions/96883",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/44220/"
] |
Everything old becomes new again.
Your invention would bring back the use of mustard gas and other airborne poisons on the battlefield.
|
A human being is weak and fleshy, and is limited to converting 3000 Calories into energy per day.
A motorcycle engine can convert 6000 Calories into energy per hour.
A high speed tankette is probably what you're going to end up with.
Not Roman Captain America.
<https://en.wikipedia.org/wiki/Tankette>
|
96,883 |
Humans have finally developed a shield completely made out of handwavium. Hurrah! This shield is unbreakable except to anti-tank rounds, RPGS, and other heavy weapons. Assuming the army could afford giving half of their troops handwavium shields, how would this change how modern (2017) infantry moves and takes cover? Assume the shield weighs about 40 pounds and have the same dimensions as a tower shield.
|
2017/11/03
|
[
"https://worldbuilding.stackexchange.com/questions/96883",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/44220/"
] |
I think it would not change much in modern warfare, as the current trend is less based on infantry combat. They would improve the existent uses of shields in military and police activity, but not change the tactics, as most tactics involve long distance, high-tech (drones), or explosive power. So it would just be used in the same scenarios shields are already used.
The material on the other hand could be used for many different things. Even if you can't forge precise forms you can enhance vehicle plating, body armour in smaller pieces to stop bullets.
But except for guerilla fights tower shields will not have an impact. And there it is only changing effectiveness and not tactics. (Modern shields are already almost impenetrable, after all)
|
If such shields were adopted, the result would simply be wider usage of mortars and automatic grenade launchers. Mortar bombs can explode behind or above a warfighter as well as before him, thus negating the shield. Grenades just plain destroy the shield and kill its user.
|
96,883 |
Humans have finally developed a shield completely made out of handwavium. Hurrah! This shield is unbreakable except to anti-tank rounds, RPGS, and other heavy weapons. Assuming the army could afford giving half of their troops handwavium shields, how would this change how modern (2017) infantry moves and takes cover? Assume the shield weighs about 40 pounds and have the same dimensions as a tower shield.
|
2017/11/03
|
[
"https://worldbuilding.stackexchange.com/questions/96883",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/44220/"
] |
I think it would not change much in modern warfare, as the current trend is less based on infantry combat. They would improve the existent uses of shields in military and police activity, but not change the tactics, as most tactics involve long distance, high-tech (drones), or explosive power. So it would just be used in the same scenarios shields are already used.
The material on the other hand could be used for many different things. Even if you can't forge precise forms you can enhance vehicle plating, body armour in smaller pieces to stop bullets.
But except for guerilla fights tower shields will not have an impact. And there it is only changing effectiveness and not tactics. (Modern shields are already almost impenetrable, after all)
|
The military doesn't supply everyone with the new hotness shield because some infantry will be slowed down by it. In WW2 soldier packs were supposedly already 90lbs. Do you seriously think that an infantryman wants to carry another 40lbs of cover with them at all times? That's 130lbs.. Weight is heavy.
Right now the units who do use shields in general are swat and riot people. Swat and riot people will get safer, however even they won't all switch to these 40lbs shields because it would make things more dangerous for the people their fighting. Imagine how hard it will be to not hurt rioting civilians if you have to move a 40lbs shield in a shield wall? SWAT doesn't even always use shields anyway. At the end of the day this will become a nice tool that the military has, but it won't be made standard.
Now if you put this in a vest on the other hand it would be used, but the tactics used with it would remain the same as tactics already used with heavy vests today.
|
96,883 |
Humans have finally developed a shield completely made out of handwavium. Hurrah! This shield is unbreakable except to anti-tank rounds, RPGS, and other heavy weapons. Assuming the army could afford giving half of their troops handwavium shields, how would this change how modern (2017) infantry moves and takes cover? Assume the shield weighs about 40 pounds and have the same dimensions as a tower shield.
|
2017/11/03
|
[
"https://worldbuilding.stackexchange.com/questions/96883",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/44220/"
] |
Shield-equipped troops, so safe against rifle bullets, meet the device called a "land mine".
Shield-equipped troops, glad you're protected against shrapnel from exploding artillery rounds. Let us introduce you to this thing called "blast wave". Or better yet, this thing called "airburst".
Shield-equipped troops, glad you're protected from people shooting you from the front. Allow us to introduce the tactic called "flanking".
Shield-equipped troops, so glad your shield can stop a bullet. How's it handle a tank driving over you?
Shield-equipped troops, thank you kindly for carrying a big-ass target making it easier to see you to drop napalm on you.
|
If such shields were adopted, the result would simply be wider usage of mortars and automatic grenade launchers. Mortar bombs can explode behind or above a warfighter as well as before him, thus negating the shield. Grenades just plain destroy the shield and kill its user.
|
96,883 |
Humans have finally developed a shield completely made out of handwavium. Hurrah! This shield is unbreakable except to anti-tank rounds, RPGS, and other heavy weapons. Assuming the army could afford giving half of their troops handwavium shields, how would this change how modern (2017) infantry moves and takes cover? Assume the shield weighs about 40 pounds and have the same dimensions as a tower shield.
|
2017/11/03
|
[
"https://worldbuilding.stackexchange.com/questions/96883",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/44220/"
] |
I think it would not change much in modern warfare, as the current trend is less based on infantry combat. They would improve the existent uses of shields in military and police activity, but not change the tactics, as most tactics involve long distance, high-tech (drones), or explosive power. So it would just be used in the same scenarios shields are already used.
The material on the other hand could be used for many different things. Even if you can't forge precise forms you can enhance vehicle plating, body armour in smaller pieces to stop bullets.
But except for guerilla fights tower shields will not have an impact. And there it is only changing effectiveness and not tactics. (Modern shields are already almost impenetrable, after all)
|
A human being is weak and fleshy, and is limited to converting 3000 Calories into energy per day.
A motorcycle engine can convert 6000 Calories into energy per hour.
A high speed tankette is probably what you're going to end up with.
Not Roman Captain America.
<https://en.wikipedia.org/wiki/Tankette>
|
96,883 |
Humans have finally developed a shield completely made out of handwavium. Hurrah! This shield is unbreakable except to anti-tank rounds, RPGS, and other heavy weapons. Assuming the army could afford giving half of their troops handwavium shields, how would this change how modern (2017) infantry moves and takes cover? Assume the shield weighs about 40 pounds and have the same dimensions as a tower shield.
|
2017/11/03
|
[
"https://worldbuilding.stackexchange.com/questions/96883",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/44220/"
] |
Everything old becomes new again.
Your invention would bring back the use of mustard gas and other airborne poisons on the battlefield.
|
If such shields were adopted, the result would simply be wider usage of mortars and automatic grenade launchers. Mortar bombs can explode behind or above a warfighter as well as before him, thus negating the shield. Grenades just plain destroy the shield and kill its user.
|
96,883 |
Humans have finally developed a shield completely made out of handwavium. Hurrah! This shield is unbreakable except to anti-tank rounds, RPGS, and other heavy weapons. Assuming the army could afford giving half of their troops handwavium shields, how would this change how modern (2017) infantry moves and takes cover? Assume the shield weighs about 40 pounds and have the same dimensions as a tower shield.
|
2017/11/03
|
[
"https://worldbuilding.stackexchange.com/questions/96883",
"https://worldbuilding.stackexchange.com",
"https://worldbuilding.stackexchange.com/users/44220/"
] |
I think it would not change much in modern warfare, as the current trend is less based on infantry combat. They would improve the existent uses of shields in military and police activity, but not change the tactics, as most tactics involve long distance, high-tech (drones), or explosive power. So it would just be used in the same scenarios shields are already used.
The material on the other hand could be used for many different things. Even if you can't forge precise forms you can enhance vehicle plating, body armour in smaller pieces to stop bullets.
But except for guerilla fights tower shields will not have an impact. And there it is only changing effectiveness and not tactics. (Modern shields are already almost impenetrable, after all)
|
A 40 lb shield on top of the average **45 lb pack** the infantry is already carrying around would be too much of a burden for most soldiers. Since its made out of handwavium, you could make it a lot lighter.
In addition, the bulk of a tower shield is way too much; and for most soldiers bunkered down in the line of fire they would be on the ground firing back with their profile a lot smaller. Only if they were to do a charge assault would a large shield make it worthwhile.
The shape of a tower shield would not fit the requirements of a trooper lying down. They would need something that works with their weapon:
[](https://i.stack.imgur.com/3vEWo.jpg)
Again, since its handwavium, you might as well go more high-tech and work on a portable shield that expands when required.
[](https://i.ytimg.com/vi/CJ0unSMWtsk/maxresdefault.jpg)
|
43,860,679 |
I am performing some reordering in a couple of array list, I have an adapter called
>
> adapterMeasureEvi
>
>
>
which is set to a static `ArrayList` called `measureEviArray` from `DataIpat` class.
When debugging I can see that the static list is been assigned properly and it follows a notification to the adapter that the list has changed.
```
DataIpat.measureEviArray = (ArrayList<MeasureEvi>)measureEviArray.clone();
adapterMeasureEvi.notifyDataSetChanged();
```
Problem is, when `getView()` method gets called the first item it brings is from the old list, when I look up into the objects their indexes have changed that means I have updated the attributes but why is it still stuck on the old list?
/////EDIT////
I just noticed on the constructor of the adapter class that the list is definitely the old one.
```
public MeasureTableAdapter(Activity context, ArrayList<MeasureEvi> myMeasureEvi) {
super(context, R.layout.adapter_tablamedida_item, myMeasureEvi);
this.context = context;
this.myMeasureEvi = myMeasureEvi;
}
```
this constructor is called just once when the object is instantiated, so I suppose it means it will be stuck there, how can I update that list?
|
2017/05/09
|
[
"https://Stackoverflow.com/questions/43860679",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4910896/"
] |
MarkLogic 8 currently caches `user data` at `/var/local/mlcmd.conf`. The documentation says `usr/local/mlcmd.conf`. (<https://docs.marklogic.com/8.0/guide/ec2/CloudFormation>)
`/etc/sysconfig/MarkLogic` runs `init-config.sh` (I couldn't find the path of that file), which is said in a comment to write to `/var/local/mlcmd.conf`.
`. init-config.sh # sets up /var/local/mlcmd.conf and exports marklogic variables`
|
MarkLogic does not 'cache user-data'. The scripts referenced (/opt/MarkLogic/mlcmd/\*) do read from user-data, as well as other configuration sources such as /etc/marklogic.conf. What is 'cached' in /var/local/mlcmd.conf is the resolved values of the variables documented in <https://docs.marklogic.com/8.0/guide/ec2/CloudFormation#id_10855> after first initialization of a managed cluster node. This is intentionally put on the root filesystem so that the lifespan follows the lifecycle of the EC2 instance. If an instance is terminated and another created to take its place the file will no longer exist and the values re-resolved. While the documentation focuses on CloudFormation and User Data, none of this has any dependency on either.
|
391,559 |
Before *execution* settled into its modern meanings of "running a piece of software" and "state-organised killing", it was a much more general term for acting and doing. In this now outdated context, one could "do an execution on" something or someone, meaning roughly the same as "fix it", "do a number on it" or "lick it into shape".
I'm just not sure that *doing* is the right verb. Does one "*do* an execution" on something, "*work* an execution" on something, "*wreak* an execution" on something, or should it be some other verb I haven't thought of?
|
2017/05/29
|
[
"https://english.stackexchange.com/questions/391559",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/153997/"
] |
>
> a Pollyanna
>
>
>
is a
>
> [person characterized by irrepressible optimism and a tendency to find good in everything](https://www.merriam-webster.com/dictionary/Pollyanna) or pollyannish, after the title character of a novel displaying such properties.
>
>
>
Machiavellian isn't necessarily malevolent or paranoid, just realistic or realpolitik, but in the instances where one would contrast with the other extreme, 'pollyanna' usually fits.
|
**Lincolnian**
Abraham Lincoln was a moral and virtous leader, but also a strategic and cunning commander in chief. He assembled a “team of rivals”, which indicates a willingness to entertain opposing viewpoints as well as the involvement of others in decision-making. With fortitude, political savvy, and moral rectitude he signed the Emancipation Proclamation that freed four million people from chattel slavery. He was altruism personified. Finally, like Machiavelli, Lincoln was a leader known as much for his words as his deeds. A gifted orator and writer, his speeches are read the world over to this day.
|
391,559 |
Before *execution* settled into its modern meanings of "running a piece of software" and "state-organised killing", it was a much more general term for acting and doing. In this now outdated context, one could "do an execution on" something or someone, meaning roughly the same as "fix it", "do a number on it" or "lick it into shape".
I'm just not sure that *doing* is the right verb. Does one "*do* an execution" on something, "*work* an execution" on something, "*wreak* an execution" on something, or should it be some other verb I haven't thought of?
|
2017/05/29
|
[
"https://english.stackexchange.com/questions/391559",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/153997/"
] |
"Christlike", as people of the Christian persuasion would often argue that Jesus Christ's leadership style is that of self sacrifice and love.
Note that skeptics might argue that a strong theme underlying this claimed virtuosity is the threat of eternal damnation for those who refuse to follow Him (thereby, being ironically "Machiavellian" in nature itself).
I do not wish to discuss the merits of the opposing views or get into a religious debate, but would rather point out that depending on your intended audience, "Christlike" might or might not be the adjective you are looking for.
|
Jeffersonian
From Dictionary.com:
pertaining to or advocating the political principles and doctrines of Thomas Jefferson, especially those stressing minimum control by the central government, the inalienable rights of the individual, and the superiority of an agrarian economy and rural society.
|
391,559 |
Before *execution* settled into its modern meanings of "running a piece of software" and "state-organised killing", it was a much more general term for acting and doing. In this now outdated context, one could "do an execution on" something or someone, meaning roughly the same as "fix it", "do a number on it" or "lick it into shape".
I'm just not sure that *doing* is the right verb. Does one "*do* an execution" on something, "*work* an execution" on something, "*wreak* an execution" on something, or should it be some other verb I haven't thought of?
|
2017/05/29
|
[
"https://english.stackexchange.com/questions/391559",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/153997/"
] |
"Christlike", as people of the Christian persuasion would often argue that Jesus Christ's leadership style is that of self sacrifice and love.
Note that skeptics might argue that a strong theme underlying this claimed virtuosity is the threat of eternal damnation for those who refuse to follow Him (thereby, being ironically "Machiavellian" in nature itself).
I do not wish to discuss the merits of the opposing views or get into a religious debate, but would rather point out that depending on your intended audience, "Christlike" might or might not be the adjective you are looking for.
|
Strictly speaking, we are looking for the antonym of a writer, who advised a prince, or wrote in that form. That rules out many of the candidates so far. The writer has to be a household word for the ideas s/he put forward, as is M. That rules out many of the candidates so far. Churchill, Mandela and Ghandi were political actors in their own right. *Ghandian* is perhaps the best candidate, because, though he was a political actor himself, he also wrote and had a significant political idea. And he was successful at least once. And his name is widely associated with ideas that are in strong contrast with those of Machiavelli.
Confucius would be perfect except that Confucianism has become associated with something nearer to a faith, even though, properly understood, it concerns good governance.
There is one other who, rather like Machiavelli, tried to educate a head of state, but in his own uncompromising ideas of justice and law: Plato in the early 4th century BCE, reluctantly agreed to educate the future and later tyrant of Sicily, Dionysius II of Syracuse. It was a complete failure, and Dionysius proved as spectacular a monsters as several in the last an present centuries. Plato strongly contrasts with Machiavelli, both in his political ideas and in his success in promoting them. The adjective ‘Platonic’ is even widely known. However, it is already known for something else: a loving **non-sexual** relationship.
*Panglossian*. was a witty idea, which would fit well, were Voltaire’s character better known. It is found in dictionaries, and its usage does bring it as close as I could imagine to being an antonym for Machiavellian.
Another comic alternative might be *quixotic*. Quixote was the polar opposite of the prince of Machiavelli: an overeducated idealistic has-been *ingenue*.
My money would be on *quixotic*. It is the most common. Both are pejorative, and you can argue that they are the unsatisfactory extremes, with good governance as the Aristotelian happy medium between the two
|
391,559 |
Before *execution* settled into its modern meanings of "running a piece of software" and "state-organised killing", it was a much more general term for acting and doing. In this now outdated context, one could "do an execution on" something or someone, meaning roughly the same as "fix it", "do a number on it" or "lick it into shape".
I'm just not sure that *doing* is the right verb. Does one "*do* an execution" on something, "*work* an execution" on something, "*wreak* an execution" on something, or should it be some other verb I haven't thought of?
|
2017/05/29
|
[
"https://english.stackexchange.com/questions/391559",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/153997/"
] |
Before we can suggest terms that might stand as opposites to *Machiavellian*, we need to nail down what people mean by that term. Here is the entry for *Machiavellian* in *Merriam-Webster's Eleventh Collegiate Dictionary* (2003):
>
> **Machiavellian** *adj.* {Niccolo *Machiavelli*} (1572) **1 :** of or relating to Machiavelli or Machiavellianism ["the political theory of Machiavelli; *esp* : the view that politics is amoral and that any means however unscrupulous can be justifiably used in achieving political power"] 2 : suggesting the principles of conduct laid down by Machiavelli; *specif* : marked by cunning, duplicity, or bad faith
>
>
>
So we're looking for something that sums up in a single word an absence of cunning, duplicity, bad faith, unscrupulousness, deceptiveness, underhandedness, power hungriness, pursuit of a hidden agenda, amorality, and unprincipled self-interest.
There certainly are antonyms for some of these ideas: *scrupulous*, *fair*, *honest*, *upright*, *honorable*, *aboveboard*, *disinterested*, *ethical*, and *principled*, for example. But these words fail to negate (or even address) another aspect of *Machiavellian*—its incorporation of such notions as skeptical, sly, streetwise, opportunistic, flexible, realistic, and even unblinkered. The opposites of these notions are (or may be seen as) somewhat less admirable than those in the last group: *trusting*, *naive*, *rigid*, *straitlaced*, *unbending*, *impractical*, and even *deluded*.
It seems to me that the true opposite of *Machiavellian* would comprehend both groups of opposite notions listed above. The central idea of such an opposite word would be its countering of Machiavellianism's protean adaptability to circumstance in order to find and exploit an advantage by any means possible with a devotion to doing things by the book—whether that book is the Bible, [*A Short Treatise of the Game of Whist*](https://en.wikipedia.org/wiki/Edmond_Hoyle), or [*Amy Vanderbilt's Complete Book of Etiquette*](https://en.wikipedia.org/wiki/Amy_Vanderbilt).
There is one book (or written code) that has become synonymous with fair play in violent circumstances, although people in recent decades have tended to bring it up derisively, as a set of rules that the bad guys (and therefore, of necessity, we) don't abide by. I speak of the [Marquess of Queensberry Rules](https://en.wikipedia.org/wiki/Marquess_of_Queensberry_Rules)—the code of pugilism under which honorable gentlemen attempt to beat each other senseless in the most sporting way possible.
**Queensberrian** is everything that *Machiavellian* is not: strict, codified, honor-based, constrained, predictable, principled. It is also deeply artificial, denying fighters the (arguable) natural right to identify and pursue their immediate advantage by any means necessary, including fighting dirty, cheating, and exploiting forbidden unfair advantages. And unfortunately, it scarcely exists as an adjective. A Google Books search turns up a single match, from [*Our Navy, the Standard Publication of the U.S. Navy*](https://books.google.com/books?id=BYc9AQAAMAAJ&pg=RA4-PA44&dq=%22queensberrian%22&hl=en&sa=X&ved=0ahUKEwi5l8jLsJbUAhXpgVQKHXpADXMQ6AEIJTAA#v=onepage&q=%22queensberrian%22&f=false) (April 1917):
>
> HOW THINGS BROKE FOR OUR SCRAPPY SHIPMATES LAST MONTH.
>
>
> Events pugilistic, as applied to our numerous sea-Faring shipmates who seek **Queensberrian** glory while serving under the Union Jack, were well seasoned last month. Seasoned with wins, losses, draws and ALSO SOME PUNKERINO DECISIONS on the part of some poor blind men who, pitied by fight promoters, were given jobs as referees or judges.
>
>
>
An Elephind search turns up a second instance of the term, from "[Dempsey's Legs Hold Answer](http://idnc.library.illinois.edu/cgi-bin/illinois?a=d&d=DKD19260819.1.7&txq=%22queensberrian%22)," in the *DeKalb [Illinois] Daily Chronicle* (August 19, 1926):
>
> Within the week I have talked with two former champions who tried to "come back," just as [Jack] Dempsey is trying, after an extended abstinence from the **Queensberrian** feasts.
>
>
>
More regrettable still, both of these instances of *Queensberrian* use the term to mean, essentially, "boxing-related." But the word is so little used that you could easily repurpose it to mean "anti-Machiavellian"—performed in accordance with high-minded rules of conduct that may or may not have anything in common with how people actually behave when left to their own devices.
|
One option is **Confucian**. What constitutes good government is an essential question with which Confucian thought concerns itself, and its methods and foundations are the opposite of your "Machiavellian": Confucianism emphasises that human nature is fundamentally good, that one must practice virtue in daily life, and that harmony and loyalty are essential in a well governed community.
>
> Confucianism, also known as Ruism, is described as tradition, a philosophy, a religion, a humanistic or rationalistic religion, **a way of governing**, or simply a way of life.
>
>
> ...
>
>
> The this-worldly concern of Confucianism rests on the belief that human beings are fundamentally good, and teachable, improvable, and perfectible through personal and communal endeavor especially self-cultivation and self-creation. Confucian thought focuses on the cultivation of virtue and maintenance of ethics.
>
>
>
<https://en.wikipedia.org/wiki/Confucianism>
|
391,559 |
Before *execution* settled into its modern meanings of "running a piece of software" and "state-organised killing", it was a much more general term for acting and doing. In this now outdated context, one could "do an execution on" something or someone, meaning roughly the same as "fix it", "do a number on it" or "lick it into shape".
I'm just not sure that *doing* is the right verb. Does one "*do* an execution" on something, "*work* an execution" on something, "*wreak* an execution" on something, or should it be some other verb I haven't thought of?
|
2017/05/29
|
[
"https://english.stackexchange.com/questions/391559",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/153997/"
] |
Before we can suggest terms that might stand as opposites to *Machiavellian*, we need to nail down what people mean by that term. Here is the entry for *Machiavellian* in *Merriam-Webster's Eleventh Collegiate Dictionary* (2003):
>
> **Machiavellian** *adj.* {Niccolo *Machiavelli*} (1572) **1 :** of or relating to Machiavelli or Machiavellianism ["the political theory of Machiavelli; *esp* : the view that politics is amoral and that any means however unscrupulous can be justifiably used in achieving political power"] 2 : suggesting the principles of conduct laid down by Machiavelli; *specif* : marked by cunning, duplicity, or bad faith
>
>
>
So we're looking for something that sums up in a single word an absence of cunning, duplicity, bad faith, unscrupulousness, deceptiveness, underhandedness, power hungriness, pursuit of a hidden agenda, amorality, and unprincipled self-interest.
There certainly are antonyms for some of these ideas: *scrupulous*, *fair*, *honest*, *upright*, *honorable*, *aboveboard*, *disinterested*, *ethical*, and *principled*, for example. But these words fail to negate (or even address) another aspect of *Machiavellian*—its incorporation of such notions as skeptical, sly, streetwise, opportunistic, flexible, realistic, and even unblinkered. The opposites of these notions are (or may be seen as) somewhat less admirable than those in the last group: *trusting*, *naive*, *rigid*, *straitlaced*, *unbending*, *impractical*, and even *deluded*.
It seems to me that the true opposite of *Machiavellian* would comprehend both groups of opposite notions listed above. The central idea of such an opposite word would be its countering of Machiavellianism's protean adaptability to circumstance in order to find and exploit an advantage by any means possible with a devotion to doing things by the book—whether that book is the Bible, [*A Short Treatise of the Game of Whist*](https://en.wikipedia.org/wiki/Edmond_Hoyle), or [*Amy Vanderbilt's Complete Book of Etiquette*](https://en.wikipedia.org/wiki/Amy_Vanderbilt).
There is one book (or written code) that has become synonymous with fair play in violent circumstances, although people in recent decades have tended to bring it up derisively, as a set of rules that the bad guys (and therefore, of necessity, we) don't abide by. I speak of the [Marquess of Queensberry Rules](https://en.wikipedia.org/wiki/Marquess_of_Queensberry_Rules)—the code of pugilism under which honorable gentlemen attempt to beat each other senseless in the most sporting way possible.
**Queensberrian** is everything that *Machiavellian* is not: strict, codified, honor-based, constrained, predictable, principled. It is also deeply artificial, denying fighters the (arguable) natural right to identify and pursue their immediate advantage by any means necessary, including fighting dirty, cheating, and exploiting forbidden unfair advantages. And unfortunately, it scarcely exists as an adjective. A Google Books search turns up a single match, from [*Our Navy, the Standard Publication of the U.S. Navy*](https://books.google.com/books?id=BYc9AQAAMAAJ&pg=RA4-PA44&dq=%22queensberrian%22&hl=en&sa=X&ved=0ahUKEwi5l8jLsJbUAhXpgVQKHXpADXMQ6AEIJTAA#v=onepage&q=%22queensberrian%22&f=false) (April 1917):
>
> HOW THINGS BROKE FOR OUR SCRAPPY SHIPMATES LAST MONTH.
>
>
> Events pugilistic, as applied to our numerous sea-Faring shipmates who seek **Queensberrian** glory while serving under the Union Jack, were well seasoned last month. Seasoned with wins, losses, draws and ALSO SOME PUNKERINO DECISIONS on the part of some poor blind men who, pitied by fight promoters, were given jobs as referees or judges.
>
>
>
An Elephind search turns up a second instance of the term, from "[Dempsey's Legs Hold Answer](http://idnc.library.illinois.edu/cgi-bin/illinois?a=d&d=DKD19260819.1.7&txq=%22queensberrian%22)," in the *DeKalb [Illinois] Daily Chronicle* (August 19, 1926):
>
> Within the week I have talked with two former champions who tried to "come back," just as [Jack] Dempsey is trying, after an extended abstinence from the **Queensberrian** feasts.
>
>
>
More regrettable still, both of these instances of *Queensberrian* use the term to mean, essentially, "boxing-related." But the word is so little used that you could easily repurpose it to mean "anti-Machiavellian"—performed in accordance with high-minded rules of conduct that may or may not have anything in common with how people actually behave when left to their own devices.
|
I have been trying to break this down for some time now. Here are my thoughts…
It is my understanding that the definition of the traits found to be “Machiavellian” in nature contain both negative and positive aspects. To me, that is the heart of the reason why it is difficult to ascertain a true opposite.
Here is where I am right now. If you take Machiavellian behaviors, they are categorized as:
Negative Traits: amoral, unscrupulous, cunning, duplicitous, deceitful, manipulative
Positive Traits: Strategic, goal-oriented, planning
The opposite I would postulate could be:
Anti-Negative Traits: Moral, judicious, transparent, collaborative, open, authentic and trustworthy
Anti-Positive Traits: Directionless, lethargic, content, satisfied, and unprepared
I would think that the singularly best term that fits as an anti-Machiavellian would be "Hippie", or as Dictionary.com describes them, "a person... who rejected established institutions and values and sough spotaneity, direct personal relations expressing love, and expanded consciousness"
Thoughts?
|
391,559 |
Before *execution* settled into its modern meanings of "running a piece of software" and "state-organised killing", it was a much more general term for acting and doing. In this now outdated context, one could "do an execution on" something or someone, meaning roughly the same as "fix it", "do a number on it" or "lick it into shape".
I'm just not sure that *doing* is the right verb. Does one "*do* an execution" on something, "*work* an execution" on something, "*wreak* an execution" on something, or should it be some other verb I haven't thought of?
|
2017/05/29
|
[
"https://english.stackexchange.com/questions/391559",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/153997/"
] |
Call me cynical, but my candidate is ***quixotic***. [Merriam-Webster](https://www.merriam-webster.com/dictionary/quixotic) says:
>
> foolishly impractical especially in the pursuit of ideals; especially
> : marked by rash lofty romantic ideas or extravagantly chivalrous
> action.
>
>
>
The word is derived from the name Don Quixote, the hero of a 17th century novel by Cervantes, and, according to M-W (link above)
>
> ....has been used to describe unrealistic idealists since at least the
> early 18th century.
>
>
>
My cynical point is that anyone who is successful cannot be entirely free from
Machiavellian behavior (in the modern sense) all the time.
|
**Lincolnian**
Abraham Lincoln was a moral and virtous leader, but also a strategic and cunning commander in chief. He assembled a “team of rivals”, which indicates a willingness to entertain opposing viewpoints as well as the involvement of others in decision-making. With fortitude, political savvy, and moral rectitude he signed the Emancipation Proclamation that freed four million people from chattel slavery. He was altruism personified. Finally, like Machiavelli, Lincoln was a leader known as much for his words as his deeds. A gifted orator and writer, his speeches are read the world over to this day.
|
391,559 |
Before *execution* settled into its modern meanings of "running a piece of software" and "state-organised killing", it was a much more general term for acting and doing. In this now outdated context, one could "do an execution on" something or someone, meaning roughly the same as "fix it", "do a number on it" or "lick it into shape".
I'm just not sure that *doing* is the right verb. Does one "*do* an execution" on something, "*work* an execution" on something, "*wreak* an execution" on something, or should it be some other verb I haven't thought of?
|
2017/05/29
|
[
"https://english.stackexchange.com/questions/391559",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/153997/"
] |
Note, the present nuance of the question is:
*"with equivalent cultural weight and recognition..."*
======================================================
Indeed, really the only one I can think of is Churchill, or possibly Gandhi (but Gandhi is just so different, not an "opposite").
I can't really think of any, at all, historical, classical figures who are a trope for "good, decent politics" (which is pretty disappointing!) *Maybe* Elizabeth 1, and that's a stretch.
---
Might as well throw in an answer, I'd go with
Churchillian
============
Obvious, right?
Why is it a good *possible* choice?
It occurred to me: quite simply, among "negative" eponymous adjectives ... quite simply, **the most well-known "negative" eponymous adjective**, in the political milieu, is indeed Machiavellian.
So....
among "positive" eponymous adjectives ... **quite simply the most well-known "positive" eponymous adjective**, in the political milieu, is indeed .... Churchillian.
If you were trying to explain to a 6 year old Machiavellian, you'd really just say ......... "bad". (Subtleties like "scheming", "devilishly clever" etc wouldn't be relevant at the simplest level of definition of Machiavellian.) Similarly for Churchill, plain "good".
So Machiavelli - very basic "bad" trope, Churchill, very basic "good" trope.
On the "good" side, the only other political figures for 5000 years I can think of that are a basic trope of "good" is "Gandi-esque" (but he was just a completely different type of political figure, it doesn't fit), and maybe Good King Wenceslas. (Kind of a damming commentary on 5000 years of leaders!)
(On the evil side you have "Hitler", "Mao", "Stalin" (way to go, 20th century, just lovely) and, really, a broad choice of historical figures :O )
As a bonus ....
===============
Nicely, Churchill and Machiavelli were *the same type of thing* ...
They were both "real politicians", both "real operators", both central to Language and writing, both gambled at Monaco, married beautiful Americans, drank Scotch all day, greatest orators, etc - but, nicely, Churchill was a "good" guy (for the six-year old explanation); Machiavelli a "bad" guy (for the six-year old explanation).
Note that, say, "Hitleristic" is not an antonym to "Churchillian" - they're just totally different sorts of things. Churchill was just an ordinary politician, with good and bad speeches; Hitler of course was a despotic madman.
Similarly, for an antonym to "Machiavellian" you wouldn't say "Christ-like" or "Buddha-like" - it's just a whole different thing.
So again - let us say, almost setting aside the very subtle shades of meaning, "Machiavellian" is simply the outright most-used negative ("most infamous") political eponymous adjective; Churchillian is the most-used positive ("most positively famous") political eponymous adjective.
So in many ways it's a good choice - it's the "trope choice" if you will.
Does it pass the **sitcom test**? Yes; "George is acting rather Churchillian today, Kramer." "More like Machiavellian, Jerry!"
|
I don't think there really is an antonym, especially a positive one. Though perhaps that's my personal bias showing, as I don't consider Machivellian particularly negative :-)
But in a certain sense, perhaps Panglossian, after the character in Voltaire's "Candide" to whom "all is for the best in this best of possible worlds".
|
391,559 |
Before *execution* settled into its modern meanings of "running a piece of software" and "state-organised killing", it was a much more general term for acting and doing. In this now outdated context, one could "do an execution on" something or someone, meaning roughly the same as "fix it", "do a number on it" or "lick it into shape".
I'm just not sure that *doing* is the right verb. Does one "*do* an execution" on something, "*work* an execution" on something, "*wreak* an execution" on something, or should it be some other verb I haven't thought of?
|
2017/05/29
|
[
"https://english.stackexchange.com/questions/391559",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/153997/"
] |
**Christian** has been used in this way. The following defintions from [dictionary.com](http://www.dictionary.com/browse/christian) are relevant:
>
> 4. exhibiting a spirit proper to a follower of Jesus Christ; Christlike:
> *She displayed true Christian charity.*
> 5. decent; respectable:
> *They gave him a good Christian burial.*
> 6. human; not brutal; humane:
> *Such behavior isn't Christian.*
>
>
>
and
>
> 8. a person who exemplifies in his or her life the teachings of Christ:
> *He died like a true Christian*.
>
>
>
|
**saint-like**
**he's a Saint** - **she's a saint** both strongly suggest that the person goes out of their way to help others .. to an extreme of self-sacrifice
**Mother Teresa** had it's time in the sun, although it was so frequently used in the "I'm no Mother Teresa" or (I'm no saint) way, and it was a term that does not seem to be standing the test of time
|
391,559 |
Before *execution* settled into its modern meanings of "running a piece of software" and "state-organised killing", it was a much more general term for acting and doing. In this now outdated context, one could "do an execution on" something or someone, meaning roughly the same as "fix it", "do a number on it" or "lick it into shape".
I'm just not sure that *doing* is the right verb. Does one "*do* an execution" on something, "*work* an execution" on something, "*wreak* an execution" on something, or should it be some other verb I haven't thought of?
|
2017/05/29
|
[
"https://english.stackexchange.com/questions/391559",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/153997/"
] |
Jeffersonian
From Dictionary.com:
pertaining to or advocating the political principles and doctrines of Thomas Jefferson, especially those stressing minimum control by the central government, the inalienable rights of the individual, and the superiority of an agrarian economy and rural society.
|
[Good Samaritan](http://www.thefreedictionary.com/good+Samaritan)
n.
A compassionate person who unselfishly helps others, especially strangers.
Good Samaritan deeds are opposite to the selfish deeds exhibited by Machiavellian characters.
|
391,559 |
Before *execution* settled into its modern meanings of "running a piece of software" and "state-organised killing", it was a much more general term for acting and doing. In this now outdated context, one could "do an execution on" something or someone, meaning roughly the same as "fix it", "do a number on it" or "lick it into shape".
I'm just not sure that *doing* is the right verb. Does one "*do* an execution" on something, "*work* an execution" on something, "*wreak* an execution" on something, or should it be some other verb I haven't thought of?
|
2017/05/29
|
[
"https://english.stackexchange.com/questions/391559",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/153997/"
] |
Call me cynical, but my candidate is ***quixotic***. [Merriam-Webster](https://www.merriam-webster.com/dictionary/quixotic) says:
>
> foolishly impractical especially in the pursuit of ideals; especially
> : marked by rash lofty romantic ideas or extravagantly chivalrous
> action.
>
>
>
The word is derived from the name Don Quixote, the hero of a 17th century novel by Cervantes, and, according to M-W (link above)
>
> ....has been used to describe unrealistic idealists since at least the
> early 18th century.
>
>
>
My cynical point is that anyone who is successful cannot be entirely free from
Machiavellian behavior (in the modern sense) all the time.
|
Platonic - without ulterior motive, peaceful intent
|
13,092,696 |
I am trying to set an image with size of 960x640 pixels... My device has 854x480 pixels..
What I have done is to load the sprite, and then set as scene background...
```
sprite = new Sprite(0, 0, fieldITexture, BaseActivity.getSharedInstance().getVertexBufferObjectManager());
setBackground(new SpriteBackground(sprite));
```
But obviusly that image is getting outside of screen, i tried to use setScale and setScaleCenter, but i does not give any result... See this image: <http://db.tt/pcuJa4vE>
To set camera size, i have done it depending on the device:
```
final Display display = getWindowManager().getDefaultDisplay();
CAMERA_WIDTH = display.getWidth();
CAMERA_HEIGHT = display.getHeight();
mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), mCamera);
```
So, what can I do to scale the football field to the screen size? I dont care about aspect
|
2012/10/26
|
[
"https://Stackoverflow.com/questions/13092696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1354096/"
] |
Don't use device.getWitdh() and device.getHeight() use fixed width and height
```
public final static int CAMERA_WIDTH = 720;
public final static int CAMERA_HEIGHT = 480;
```
AndEngine will scale all the images for you, sometimes you will see a small black bar around the edges of the screen because of the scaling. but almost not noticable.
```
@Override
public EngineOptions onCreateEngineOptions()
{
camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new FillResolutionPolicy(), camera);
return engineOptions;
}
```
|
just to put it out there, I believe there are 2 major ratio's (5:3 and 4:3) for the devices.
Most others are closer to 5:3 than 4:3 (so 5:3 should be default).
I wanted to support the best graphics possible, without having to go through ALL screen sizes.
So i took those 2 ratios.
Now I made my setup like this:
define
```
String fileFolderForRatio = "";
int CAMERA_WIDTH = 1280;
int CAMERA_HEIGHT = 768;
@Override
public EngineOptions onCreateEngineOptions() {
instance = this;
// getting the device's screen size
Point screenSize = getScreenSizeByRatio();
CAMERA_WIDTH = screenSize.x;
CAMERA_HEIGHT = screenSize.y;
mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE_SENSOR,
new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), mCamera);
engineOptions.getAudioOptions().setNeedsSound(true);
engineOptions.getAudioOptions().setNeedsMusic(true);
return engineOptions;
}
```
and the function (note the check for wide and height, sometimes AndEngine detects it the other way around)
```
public Point getScreenSizeByRatio()
{
final Display display = getWindowManager().getDefaultDisplay();
double sw = display.getWidth();
double sh = display.getHeight();
double ratio = sw / sh;
if (sw < sh) ratio = sh/sw;
Point screenPoints = new Point();
if (ratio > 1.3 && ratio < 1.4)
{
fileFolderForRatio = "1024x768";
screenPoints.x = 1024;
screenPoints.y = 768;
} else
{
fileFolderForRatio = "1280x768";
screenPoints.x = 1280;
screenPoints.y = 768;
}
Debug.e("RATIO", fileFolderForRatio);
return screenPoints;
}
```
Put the graphics (optimized for that screen size) in the 1024x768 folder and the 1280x768 folder.
This way you have semi-static screensize.
AndEngine will resize the rest for you.
(please not that for screen positioning of sprites you'll have to check as it's not the same for the 2 ratio's.
But coming from a Ios developer it's not that difficult (iPad and iPhone)
Hope it helps
|
13,092,696 |
I am trying to set an image with size of 960x640 pixels... My device has 854x480 pixels..
What I have done is to load the sprite, and then set as scene background...
```
sprite = new Sprite(0, 0, fieldITexture, BaseActivity.getSharedInstance().getVertexBufferObjectManager());
setBackground(new SpriteBackground(sprite));
```
But obviusly that image is getting outside of screen, i tried to use setScale and setScaleCenter, but i does not give any result... See this image: <http://db.tt/pcuJa4vE>
To set camera size, i have done it depending on the device:
```
final Display display = getWindowManager().getDefaultDisplay();
CAMERA_WIDTH = display.getWidth();
CAMERA_HEIGHT = display.getHeight();
mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), mCamera);
```
So, what can I do to scale the football field to the screen size? I dont care about aspect
|
2012/10/26
|
[
"https://Stackoverflow.com/questions/13092696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1354096/"
] |
Don't use device.getWitdh() and device.getHeight() use fixed width and height
```
public final static int CAMERA_WIDTH = 720;
public final static int CAMERA_HEIGHT = 480;
```
AndEngine will scale all the images for you, sometimes you will see a small black bar around the edges of the screen because of the scaling. but almost not noticable.
```
@Override
public EngineOptions onCreateEngineOptions()
{
camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new FillResolutionPolicy(), camera);
return engineOptions;
}
```
|
Replace:
new RatioResolutionPolicy(WIDTH, HEIGHT)
with:
new FillResolutionPolicy ()
this fills up the whole screen.
|
13,092,696 |
I am trying to set an image with size of 960x640 pixels... My device has 854x480 pixels..
What I have done is to load the sprite, and then set as scene background...
```
sprite = new Sprite(0, 0, fieldITexture, BaseActivity.getSharedInstance().getVertexBufferObjectManager());
setBackground(new SpriteBackground(sprite));
```
But obviusly that image is getting outside of screen, i tried to use setScale and setScaleCenter, but i does not give any result... See this image: <http://db.tt/pcuJa4vE>
To set camera size, i have done it depending on the device:
```
final Display display = getWindowManager().getDefaultDisplay();
CAMERA_WIDTH = display.getWidth();
CAMERA_HEIGHT = display.getHeight();
mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
return new EngineOptions(true, ScreenOrientation.LANDSCAPE_FIXED, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), mCamera);
```
So, what can I do to scale the football field to the screen size? I dont care about aspect
|
2012/10/26
|
[
"https://Stackoverflow.com/questions/13092696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1354096/"
] |
just to put it out there, I believe there are 2 major ratio's (5:3 and 4:3) for the devices.
Most others are closer to 5:3 than 4:3 (so 5:3 should be default).
I wanted to support the best graphics possible, without having to go through ALL screen sizes.
So i took those 2 ratios.
Now I made my setup like this:
define
```
String fileFolderForRatio = "";
int CAMERA_WIDTH = 1280;
int CAMERA_HEIGHT = 768;
@Override
public EngineOptions onCreateEngineOptions() {
instance = this;
// getting the device's screen size
Point screenSize = getScreenSizeByRatio();
CAMERA_WIDTH = screenSize.x;
CAMERA_HEIGHT = screenSize.y;
mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);
final EngineOptions engineOptions = new EngineOptions(true, ScreenOrientation.LANDSCAPE_SENSOR,
new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), mCamera);
engineOptions.getAudioOptions().setNeedsSound(true);
engineOptions.getAudioOptions().setNeedsMusic(true);
return engineOptions;
}
```
and the function (note the check for wide and height, sometimes AndEngine detects it the other way around)
```
public Point getScreenSizeByRatio()
{
final Display display = getWindowManager().getDefaultDisplay();
double sw = display.getWidth();
double sh = display.getHeight();
double ratio = sw / sh;
if (sw < sh) ratio = sh/sw;
Point screenPoints = new Point();
if (ratio > 1.3 && ratio < 1.4)
{
fileFolderForRatio = "1024x768";
screenPoints.x = 1024;
screenPoints.y = 768;
} else
{
fileFolderForRatio = "1280x768";
screenPoints.x = 1280;
screenPoints.y = 768;
}
Debug.e("RATIO", fileFolderForRatio);
return screenPoints;
}
```
Put the graphics (optimized for that screen size) in the 1024x768 folder and the 1280x768 folder.
This way you have semi-static screensize.
AndEngine will resize the rest for you.
(please not that for screen positioning of sprites you'll have to check as it's not the same for the 2 ratio's.
But coming from a Ios developer it's not that difficult (iPad and iPhone)
Hope it helps
|
Replace:
new RatioResolutionPolicy(WIDTH, HEIGHT)
with:
new FillResolutionPolicy ()
this fills up the whole screen.
|
111,686 |
I have the following data consisting of x, y pairs and errors of y:
```
dataWithError = {{0.0333333, 0.0000122672, 0.00000173485}, {0.05, 0.0000371462,
0.00000448037}, {0.0666667, 0.0000697768, 0.00000748151},
{0.0833333, 0.000108625, 0.000010837}, {0.1, 0.000147595,
0.0000136051}, {0.116667, 0.000186599, 0.0000161483},
{0.133333, 0.000221451, 0.0000179078}, {0.15, 0.000253062, 0.0000192494}};
```
I can plot the data with error bars with:
```
ErrorListPlot[dataWithError, Joined -> True, PlotRange -> Full]
```
The result is:
[](https://i.stack.imgur.com/LYdia.png)
I need a `ListLogLogPlot` with error bars (both axes have to be logarithmic). How can that be done?
|
2016/04/01
|
[
"https://mathematica.stackexchange.com/questions/111686",
"https://mathematica.stackexchange.com",
"https://mathematica.stackexchange.com/users/19892/"
] |
You can always perform coordinate transformation yourself. There is nothing so special about `LogLogPlot`. You have to apply `Log` to your points and plot it with regular `ErrorListPlot`. Keep in mind that your error bar won't be symmetric in log-log coordinates. After that you have to draw ticks according to your new scale.
This can be overkill for log-log case, but it gives you generic algorithm how to torture your axes any way you want.
```
Needs["ErrorBarPlots`"]
plotrange={Floor@Log10@Min[#],Ceiling@Log10@Max[#]}&@dataWithError[[All,#]]&/@{1,2};
logData={{Log10[#[[1]]],Log10[#[[2]]]},ErrorBar[Log10[1+0.5#]&/@{-#[[3]]/#[[2]],#[[3]]/#[[2]]} ] }&/@dataWithError;
xticks = {#,Superscript[10,#]}&/@Range[#1,#2,1]&@@plotrange[[1]];
yticks = {#,Superscript[10,#]}&/@Range[#1,#2,1]&@@plotrange[[2]];
{xt,yt}=#~Join~({#,""}&/@Flatten[(#[[1]]+Log10[{2,3,4,5,6,7,8,9}])&/@#])&/@{xticks,yticks};
ErrorListPlot[logData, Joined -> True, PlotRange->plotrange,FrameTicks->{{yt,None},{xt,None}},Frame->True,Axes->False]
```
[](https://i.stack.imgur.com/lwISI.png)
|
In Mathematica 12, you can use the new [Around](https://reference.wolfram.com/language/ref/Around.html) function inside `ListLogLogPlot`. No need for `ErrorBarPlots` any more.
```
toPlot = Map[({#[[1]], Around[#[[2]], #[[3]]]}) &, dataWithError];
ListLogLogPlot[toPlot, Joined -> True, Frame -> True]
```

|
51,109,350 |
How to get the corresponding row of the button clicked in an Angular Material table?
Under row I mean an object where I can see all values of all cells of the row.
Something like this:
```
<ng-container matColumnDef="EditButtonCol">
<th mat-header-cell *matHeaderCellDef>EditButtonCol</th>
<td mat-cell *matCellDef="let element">
<button mat-button (click)="onEdit(CORRESPONDING-ROW)">Edit</button>
</td>
</ng-container>
```
The is a way it works:
```
<tr mat-row *matRowDef="let row; columns: displayedColumns;"
(mouseenter)="selection.select(row)"
(mouseleave)="selection.deselect(row)"
[ngClass]="{ 'selected': selection.isSelected(row)}">
</tr>
```
I use **selection** property to set the row in the `<tr>` tag when I hover cursor on a row. And then by the time the edit button is clicked the **selection.selected** prop is set and I can use it from typescript
```
onEdit() {
console.log(this.selection.selected);
}
```
But I don't like this way because if a user navigates to the "edit" button with a "tab" button and hits enter - he will be getting a wrong row or an undefined because hover never happened.
|
2018/06/29
|
[
"https://Stackoverflow.com/questions/51109350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4429157/"
] |
Try this based on my working setup. I'm sure about element but row works. I have three buttons in this column for working with member info.
[Stackblitz example](https://stackblitz.com/edit/angular-material-table-with-multi-queries)
```
<ng-container matColumnDef="EditButtonCol">
<th mat-header-cell *matHeaderCellDef> EditButtonCol </th>
<td mat-cell *matCellDef="let row">
<button mat-button (click)="viewProfile(row.member_id)">View</button>
<button mat-button (click)="deleteRecord(row.member_id)">Delete</button>
<button mat-button (click)="editRecord(row.member_id)">Edit</button>
</td>
</ng-container>
```
|
This works
```
<button mat-button (click)="onEdit(element)">Edit</button>
```
|
36,571,397 |
I need to make it so if I have a navigation bar with Home, Oil, Coal and Natural gas, when I hover over oil, it'll make the background image for that box an oil drop or something, and if I hover over coal it will have the background image for coal in that specific box.
This is my code so far, but it's currently showing same image (oil) no matter what I hover over:
```css
#NavBar ul {
border-top-left-radius: 6px;
border-bottom-left-radius: 6px;
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}
#NavBar li {
width: 100px;
float: left;
}
#NavBar li a {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
-o-transition: .5s;
-ms-transition: .5s;
-moz-transition: .5s;
-webkit-transition: .5s;
transition: .5s;
}
#NavBar a:hover {
background-color: #111;
background-image: url("billeder/olie_navbar.png");
background-size: 30px;
background-repeat: no-repeat;
background-position: center;
}
```
```html
<div id="NavBar">
<ul>
<li><a href="index.html">Hjem</a>
</li>
<li><a href="olie.html">Olie</a>
</li>
<li><a href="kul.html">Kul</a>
</li>
<li><a href="naturgas.html">Naturgas</a>
</li>
</ul>
</div>
```
|
2016/04/12
|
[
"https://Stackoverflow.com/questions/36571397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6192926/"
] |
You're wanting something client side to validate the fields before you're able to submit to the next page. Look up validation in jQuery and maybe include the "required" attribute that's been added into HTML5.
|
Add name attribute to button set required to all required fields
```
<input name="submit" type="submit" />
```
in php
```
<?php
if(isset($_POST['submit'])){
$required = array('name', 'surname', 'phone');
$error = false;
foreach($required as $field) {
if (empty($_POST[$field])) {
$error = true;
}
}
if ($error) {
write and error message and don't react to submit
} else {
if everything is done, allow to submit
}
}
?>
```
|
36,571,397 |
I need to make it so if I have a navigation bar with Home, Oil, Coal and Natural gas, when I hover over oil, it'll make the background image for that box an oil drop or something, and if I hover over coal it will have the background image for coal in that specific box.
This is my code so far, but it's currently showing same image (oil) no matter what I hover over:
```css
#NavBar ul {
border-top-left-radius: 6px;
border-bottom-left-radius: 6px;
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}
#NavBar li {
width: 100px;
float: left;
}
#NavBar li a {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
-o-transition: .5s;
-ms-transition: .5s;
-moz-transition: .5s;
-webkit-transition: .5s;
transition: .5s;
}
#NavBar a:hover {
background-color: #111;
background-image: url("billeder/olie_navbar.png");
background-size: 30px;
background-repeat: no-repeat;
background-position: center;
}
```
```html
<div id="NavBar">
<ul>
<li><a href="index.html">Hjem</a>
</li>
<li><a href="olie.html">Olie</a>
</li>
<li><a href="kul.html">Kul</a>
</li>
<li><a href="naturgas.html">Naturgas</a>
</li>
</ul>
</div>
```
|
2016/04/12
|
[
"https://Stackoverflow.com/questions/36571397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6192926/"
] |
You're wanting something client side to validate the fields before you're able to submit to the next page. Look up validation in jQuery and maybe include the "required" attribute that's been added into HTML5.
|
Try the below code
```
<?php
if(isset($_POST['submit'])){
$required = array('name', 'surname', 'phone');
$error = false;
$message='';
foreach($required as $field) {
if (empty($_POST[$field])) {
$error = true;
}
}
if ($error) {
$message = 'All fields required';
}else{
//Submit process here
}
}
?>
<?php echo $message; ?>
<form method="post" action="process.php" autocomplete="off">
Name: <input type="text" name="name"/>
Surname: <input type="text" name="surname" />
Phone: <input type="text" name="phone" />
<input type="submit" name="submit" value="Submit" />
```
|
36,571,397 |
I need to make it so if I have a navigation bar with Home, Oil, Coal and Natural gas, when I hover over oil, it'll make the background image for that box an oil drop or something, and if I hover over coal it will have the background image for coal in that specific box.
This is my code so far, but it's currently showing same image (oil) no matter what I hover over:
```css
#NavBar ul {
border-top-left-radius: 6px;
border-bottom-left-radius: 6px;
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}
#NavBar li {
width: 100px;
float: left;
}
#NavBar li a {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
-o-transition: .5s;
-ms-transition: .5s;
-moz-transition: .5s;
-webkit-transition: .5s;
transition: .5s;
}
#NavBar a:hover {
background-color: #111;
background-image: url("billeder/olie_navbar.png");
background-size: 30px;
background-repeat: no-repeat;
background-position: center;
}
```
```html
<div id="NavBar">
<ul>
<li><a href="index.html">Hjem</a>
</li>
<li><a href="olie.html">Olie</a>
</li>
<li><a href="kul.html">Kul</a>
</li>
<li><a href="naturgas.html">Naturgas</a>
</li>
</ul>
</div>
```
|
2016/04/12
|
[
"https://Stackoverflow.com/questions/36571397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6192926/"
] |
You're wanting something client side to validate the fields before you're able to submit to the next page. Look up validation in jQuery and maybe include the "required" attribute that's been added into HTML5.
|
Easiest and quickest way, You can use HTML5 `required`.
```html
<form method="post" action="process.php" autocomplete="off">
Name: <input type="text" name="name" required />
<BR>
Surname: <input type="text" name="surname" required />
<BR>
Phone: <input type="text" name="phone" required />
<BR>
Gender: Male <input type="radio" name="gender" value="1" required />
Female <input type="radio" name="gender" value="2" required />
<BR>
<input type="submit" />
</form>
```
|
62,965,995 |
Please help me with the code . How i can create alert when time runs out in this code. i want to set alert on when time runs out .
```js
function makeTimer() {
// var endTime = new Date("29 April 2018 9:56:00 GMT+01:00");
var endTime = new Date("29 April 2020 9:56:00 GMT+01:00");
endTime = (Date.parse(endTime) / 1000);
var now = new Date();
now = (Date.parse(now) / 1000);
var timeLeft = endTime - now;
var days = Math.floor(timeLeft / 86400);
var hours = Math.floor((timeLeft - (days * 86400)) / 3600);
var minutes = Math.floor((timeLeft - (days * 86400) - (hours * 3600)) / 60);
var seconds = Math.floor((timeLeft - (days * 86400) - (hours * 3600) - (minutes * 60)));
if (hours < "10") {
hours = "0" + hours;
}
if (minutes < "10") {
minutes = "0" + minutes;
}
if (seconds < "10") {
seconds = "0" + seconds;
}
$("#minutes").html(minutes + "<span>Minutes</span>");
$("#seconds").html(seconds + "<span>Seconds</span>");
}
setInterval(function() {
makeTimer();
}, 1000);
```
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="minutes"></span> <span id="seconds"></span>
```
|
2020/07/18
|
[
"https://Stackoverflow.com/questions/62965995",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6731583/"
] |
You don't need to make things complicated, when you logged in your logged in guard (i.e. auth guard).
```
import { Injectable } from '@angular/core';
import { Router, CanActivate } from '@angular/router';
import { AuthService } from './auth.service';
@Injectable()
export class AuthGuardService implements CanActivate {
constructor(public auth: AuthService, public router: Router , private sideMenuService: SideMenuService) {}
canActivate(): boolean {
if (!this.auth.isAuthenticated()) {
this.sideMenuService.sideMenuData.next({...data}); // so here you can dispatch the side menu service data .
this.router.navigate(['dashboard']); // here after authentication it
will redirect to your dashboard
page
return false;
}
return true;
}
}
}
```
so after redirect when you land on the Dashboard Page , in the Dashboard component you have also inject the sideMenu Service and subscribe the BehaviourSubject menu data field .
```
public name;
public isLoggedIn = false; // here you don't need to check login
// because you come here from auth guard
constructor(public router: Router, private cartService: CartService,
public sidenavMenuService: SidebarMenuService) {
this.checkLogin(); // same no need to check login in each
component if you use auth guard
this.name = Cookie.get('userName');
}
public ngOnInit(){
this.sideMenuService.sideMenuData.subscribe((data)=>{
// hered you get the data dynamic , you can assign to any
// component field.
});
}
public checkLogin(): any {
if(Cookie.get('authtoken')) {
this.isLoggedIn = true;
}
```
}
so that's how whenever you login every time you dispatch some dynamic data and your behaviourSubject will get updated and where ever you subscribe like in Dashboard component you will get the dynamic data.
Hope it will help.
|
The constructor is executed only one time during the creation of the page.
```
constructor(public router: Router, private cartService: CartService, public sidenavMenuService:SidebarMenuService) {
this.checkLogin();
this.name = Cookie.get('userName');
}
```
Now, according to the code, if the cookie `authtoken` is not found during the construction, there is no way your app to know if that was created by another (login) process.
You should call the `checkLogin` function and the `name` assignment right after your login cocmpletes.
|
39,431 |
[Fishstacks](http://esolangs.org/wiki/Fishstacks) is a [deadfish](http://esolangs.org/wiki/Deadfish) derivative based on a stack the stack can only hold four elements when a fifth element is pushed the bottom element is kicked out and eventually printed out to the screen.
I've come up with an interpreter in TI-BASIC for my calculator. However, I fell slightly guilty about using all four variables `ABCD`. I wonder if there could be a better way? Maybe with lists (arrays). I've just started learning about them, so I don't feel confident switching over yet. Any guidance would be appreciated.
Also, in order not to push anything to the screen until something falls off the stack, I've had to initialize variables to `-2`. This is the main reason I have not converted to arrays yet; I don't see how they could address this issue. (maybe even throw a `DOMAIN` error).
```
:ClrHome
:Disp "FISHSTACKS IDSP","INTERPRETER"
:0->I
:-2->A
:A->B
:B->C
:C->D
:Input Str1
:While I<length(Str1)
:I+1->I
:sub(Str1,I,1)->Str2
:If Str2="I"
:A+1->A
:If Str2="D"
:A-1->A
:If Str2="S"
:A^2->A
:If Str2="P" and D>-1
:Then
:Disp D
:C->D
:B->C
:A->B
:0->A
:End
:If A=256 or A=-1
:0->A
:If A=-2
:Stop
:End
```
By convention, I've represented the `STO→` character, `→` with `->`
|
2014/01/17
|
[
"https://codereview.stackexchange.com/questions/39431",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/33952/"
] |
I was asked by @Timtech to join + post an improvement. Using arrays is a lot easier to understand, and there were so many optimizations that I decided to completely re-write the code. I'm sure it could be improved by other advanced programmers like me, as I'm using several long expressions here... note that `L1` represents list #1 (`2nd` + `1` on the calculator) and `~` is the negative token.
```
:ClrHome
:Disp "FISHSTACKS IDSP","INTERPRETER
:DelVar IInput Str1
:DelVar L1~{2,2,2,2→L1
:While I<length(Str1
:I+1→I
:sub(Str1,I,1→Str2
:(Str2="I")-(Str2="D
:Ans+L1(4→L1(4
:If Str2="S
:L1(4)²→L1(4
:If Str2="P
:Then
:L1(1
:If 2+Ans
:Disp Ans
:ΔList(cumSum(L1->L1
:0->L1(4
:End
:L1(4
:If Ans=256 or Ans<0
:0->L1(4
:End
```
**Improvements**
1. Saved bytes by removing several unneeded ending parentheses and quotes
2. Used `DelVar` since it does not need a following colon
3. Used an array instead of four variables
4. Used a complex expression `:(Str2="I")-(Str2="D` saved to `Ans` to save space
5. Used `ΔList(cumSum(L1->L1` to get `L1` minus its first element
6. Several others I'm not listing due to their minisculity; mainly using `Ans` to save space and speed
|
Beyond the bad names that you are already aware of, I see a few things that could be improved.
`str1` and `str2` are bad variable names as well. They should be `str` and `chr` respectively. Those names would properly represent the data and make this code much more understandable. It would be instantly clear to anyone looking at the code that you're looping through each character of the string the user inputs.
This section of code makes no sense.
>
>
> ```
> :If Str2="P" and D>-1
> :Then
> :Disp D
> :C->D
> :B->C
> :A->C
> :0->A
> :End
>
> ```
>
>
Translated into a "normal" basic language, it looks like this.
```
If char = "P" And d > -1 Then
Print d
d = c
c = b
c = a
a = 0
End If
```
And it is instantly obvious that you only need to make the assignment to `c` once.
```
:If Str2="P" and D>-1
:Then
:Disp D
:C->D
:A->C
:0->A
:End
```
The other improvement I can see here, is that I think it makes a lot of sense to use a [For Loop](http://www.ticalc.org/programming/columns/83plus-bas/cherny/#for) instead of a While loop here. That way you wouldn't have to increment `I` manually on every iteration of the loop. It would make this little program a little cleaner.
|
39,431 |
[Fishstacks](http://esolangs.org/wiki/Fishstacks) is a [deadfish](http://esolangs.org/wiki/Deadfish) derivative based on a stack the stack can only hold four elements when a fifth element is pushed the bottom element is kicked out and eventually printed out to the screen.
I've come up with an interpreter in TI-BASIC for my calculator. However, I fell slightly guilty about using all four variables `ABCD`. I wonder if there could be a better way? Maybe with lists (arrays). I've just started learning about them, so I don't feel confident switching over yet. Any guidance would be appreciated.
Also, in order not to push anything to the screen until something falls off the stack, I've had to initialize variables to `-2`. This is the main reason I have not converted to arrays yet; I don't see how they could address this issue. (maybe even throw a `DOMAIN` error).
```
:ClrHome
:Disp "FISHSTACKS IDSP","INTERPRETER"
:0->I
:-2->A
:A->B
:B->C
:C->D
:Input Str1
:While I<length(Str1)
:I+1->I
:sub(Str1,I,1)->Str2
:If Str2="I"
:A+1->A
:If Str2="D"
:A-1->A
:If Str2="S"
:A^2->A
:If Str2="P" and D>-1
:Then
:Disp D
:C->D
:B->C
:A->B
:0->A
:End
:If A=256 or A=-1
:0->A
:If A=-2
:Stop
:End
```
By convention, I've represented the `STO→` character, `→` with `->`
|
2014/01/17
|
[
"https://codereview.stackexchange.com/questions/39431",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/33952/"
] |
Beyond the bad names that you are already aware of, I see a few things that could be improved.
`str1` and `str2` are bad variable names as well. They should be `str` and `chr` respectively. Those names would properly represent the data and make this code much more understandable. It would be instantly clear to anyone looking at the code that you're looping through each character of the string the user inputs.
This section of code makes no sense.
>
>
> ```
> :If Str2="P" and D>-1
> :Then
> :Disp D
> :C->D
> :B->C
> :A->C
> :0->A
> :End
>
> ```
>
>
Translated into a "normal" basic language, it looks like this.
```
If char = "P" And d > -1 Then
Print d
d = c
c = b
c = a
a = 0
End If
```
And it is instantly obvious that you only need to make the assignment to `c` once.
```
:If Str2="P" and D>-1
:Then
:Disp D
:C->D
:A->C
:0->A
:End
```
The other improvement I can see here, is that I think it makes a lot of sense to use a [For Loop](http://www.ticalc.org/programming/columns/83plus-bas/cherny/#for) instead of a While loop here. That way you wouldn't have to increment `I` manually on every iteration of the loop. It would make this little program a little cleaner.
|
```
:ClrHome
:Disp "FISHSTACKS IDSP","INTERPRETER"
:-{2,2,2,0->L1
:Input Str1
:For(I,1,length(Str1
:sub(Str1,I,1
:If Ans≠"P"
:Then
:(Ans="I")-(Ans="D")+L1(4)^int(e^(Ans="S"->L1(4
:If Ans≥0 and Ans≠256
:Else
:L1(1
:If 2+Ans
:Disp Ans
:augment(ΔList(cumSum(L1)),{0->L1
:End
:End
```
I was able to shorten FlyAwayBirdie's answer even more by combining some expressions, moving the overflow checking earlier to take advantage of Ans, setting L1 in fewer bytes, using a For loop, and a couple of other things. Additionally, I initialized variables to -1 instead of -2, except for the initial accumulator which starts at 0 as per the spec.
You can remove the close quotes at the ends of the lines.
Edit: Saved a couple more bytes by not saving the substring to Str2.
Edit: Fixed overflow functionality; however, undefined commands will now be recognized as "P".
|
39,431 |
[Fishstacks](http://esolangs.org/wiki/Fishstacks) is a [deadfish](http://esolangs.org/wiki/Deadfish) derivative based on a stack the stack can only hold four elements when a fifth element is pushed the bottom element is kicked out and eventually printed out to the screen.
I've come up with an interpreter in TI-BASIC for my calculator. However, I fell slightly guilty about using all four variables `ABCD`. I wonder if there could be a better way? Maybe with lists (arrays). I've just started learning about them, so I don't feel confident switching over yet. Any guidance would be appreciated.
Also, in order not to push anything to the screen until something falls off the stack, I've had to initialize variables to `-2`. This is the main reason I have not converted to arrays yet; I don't see how they could address this issue. (maybe even throw a `DOMAIN` error).
```
:ClrHome
:Disp "FISHSTACKS IDSP","INTERPRETER"
:0->I
:-2->A
:A->B
:B->C
:C->D
:Input Str1
:While I<length(Str1)
:I+1->I
:sub(Str1,I,1)->Str2
:If Str2="I"
:A+1->A
:If Str2="D"
:A-1->A
:If Str2="S"
:A^2->A
:If Str2="P" and D>-1
:Then
:Disp D
:C->D
:B->C
:A->B
:0->A
:End
:If A=256 or A=-1
:0->A
:If A=-2
:Stop
:End
```
By convention, I've represented the `STO→` character, `→` with `->`
|
2014/01/17
|
[
"https://codereview.stackexchange.com/questions/39431",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/33952/"
] |
I was asked by @Timtech to join + post an improvement. Using arrays is a lot easier to understand, and there were so many optimizations that I decided to completely re-write the code. I'm sure it could be improved by other advanced programmers like me, as I'm using several long expressions here... note that `L1` represents list #1 (`2nd` + `1` on the calculator) and `~` is the negative token.
```
:ClrHome
:Disp "FISHSTACKS IDSP","INTERPRETER
:DelVar IInput Str1
:DelVar L1~{2,2,2,2→L1
:While I<length(Str1
:I+1→I
:sub(Str1,I,1→Str2
:(Str2="I")-(Str2="D
:Ans+L1(4→L1(4
:If Str2="S
:L1(4)²→L1(4
:If Str2="P
:Then
:L1(1
:If 2+Ans
:Disp Ans
:ΔList(cumSum(L1->L1
:0->L1(4
:End
:L1(4
:If Ans=256 or Ans<0
:0->L1(4
:End
```
**Improvements**
1. Saved bytes by removing several unneeded ending parentheses and quotes
2. Used `DelVar` since it does not need a following colon
3. Used an array instead of four variables
4. Used a complex expression `:(Str2="I")-(Str2="D` saved to `Ans` to save space
5. Used `ΔList(cumSum(L1->L1` to get `L1` minus its first element
6. Several others I'm not listing due to their minisculity; mainly using `Ans` to save space and speed
|
```
:ClrHome
:Disp "FISHSTACKS IDSP","INTERPRETER"
:-{2,2,2,0->L1
:Input Str1
:For(I,1,length(Str1
:sub(Str1,I,1
:If Ans≠"P"
:Then
:(Ans="I")-(Ans="D")+L1(4)^int(e^(Ans="S"->L1(4
:If Ans≥0 and Ans≠256
:Else
:L1(1
:If 2+Ans
:Disp Ans
:augment(ΔList(cumSum(L1)),{0->L1
:End
:End
```
I was able to shorten FlyAwayBirdie's answer even more by combining some expressions, moving the overflow checking earlier to take advantage of Ans, setting L1 in fewer bytes, using a For loop, and a couple of other things. Additionally, I initialized variables to -1 instead of -2, except for the initial accumulator which starts at 0 as per the spec.
You can remove the close quotes at the ends of the lines.
Edit: Saved a couple more bytes by not saving the substring to Str2.
Edit: Fixed overflow functionality; however, undefined commands will now be recognized as "P".
|
4,211,274 |
I am trying to make an interactive, text-based connect4 game in SWI Prolog, and I'm a little stuck on how to start. What I don't understand is how to represent the game board, since I don't think I can have arrays, or variables that can be seen and modified by all rules.
Any insight as to how to start would be greatly appreciated!
|
2010/11/18
|
[
"https://Stackoverflow.com/questions/4211274",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/395986/"
] |
An appropriate representation of a data structure amenable to your situation is often half the problem in PROLOG.
There are many ways of representing things in a grid like a 2-dim array in PROLOG, but I'd argue that the easiest are probably list-based, since there is a lot of inherent support for list structures:
**1. List-of-lists.** E.g., for a 3x3, `[[a,b,c],[d,e,f],[g,h,i]]`. Your interpretation of this structure will be inherent in your code to traverse and manipulate it (i.e., `[a,b,c]` can be a row, or a column, it's up to you, just be consistent). To access an individual cell, you'd need to traverse the structure with a predicate that counts (or matches to) particular positions.
**2. List-of-terms.** E.g., `[cell(0,0,a), cell(0,1,b), ..., cell(2,2,i)]`. This would allow you to pull out individual cells directly, such as via `select(cell(1,2,Value), L, Rem)` to extract the `Value` of cell at position `1,2` from the list of cells, `L`, allowing you to manipulate it and create the full list again by creating a new `cell/3` term and appending it to `Rem`.
I would advise against using the `assert`/`retract` mechanism in writing code to handle this problem; it's messy, unnecessary, and not conducive to writing easily understandable and 'debuggable' PROLOG code.
|
(I hope you are talking about [this](http://en.wikipedia.org/wiki/Connect_Four) game).
You have a several choices.
You can have a list of lists for the whole field, like
[[empty,empty,yellow,red,empty],[red,red,red,yellow,yellow],[red,red,red,red,red]].
Or you can assert/retract facts like
red(2, 4).
red(1, 3).
yellow(2, 2).
red(3, 2).
The game is simple, so choose whatever matches your intuitive representation.
|
55,018,442 |
Currently i want to make event for "Copy to Clipboard" on user device.
When user click to "List view leading icon.content copy" then text should be store on his device clipboard.
Please can anyone help me?
```
Widget _buildListItem(BuildContext context, DocumentSnapshot data) {
final record = Record.fromSnapshot(data);
return Padding(
key: ValueKey(record.name),
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
child: Container(
decoration: BoxDecoration(
border: Border.all(color: Colors.grey),
borderRadius: BorderRadius.circular(5.0),
),
child: ListTile(
leading: Icon(Icons.content_copy),
title: Text(record.group),
subtitle: Text(record.name),
// can anyone help me how to create event on onTap action.
// When user click then text copy to clipboard on his device.
onTap: () {
debugPrint ("Tapped");
},
),
),
);
}
}
class Record {
final String name;
final String group;
final DocumentReference reference;
Record.fromMap(Map<String, dynamic> map, {this.reference})
: assert(map['name'] != null),
assert(map['group'] != null),
name = map['name'],
group = map['group'];
Record.fromSnapshot(DocumentSnapshot snapshot)
: this.fromMap(snapshot.data, reference: snapshot.reference);
@override
String toString() => "Record<$name:$group>";
}
```
|
2019/03/06
|
[
"https://Stackoverflow.com/questions/55018442",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11074663/"
] |
```
import 'package:flutter/services.dart';
```
inside your `onTap` add the following:
```
onTap:(){
Clipboard.setData(new ClipboardData(text: record.name));
Scaffold.of(context).showSnackBar(SnackBar
(content: Text('text copied')));
}
```
|
If Sami Kanafani's answer throws an exception because of the snackbar try this solution that worked for me.
```
final GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>();
...//build method
Scaffold(
key: _scaffoldKey,
appBar: _appBar,
body: _content,
floatingActionButton: FloatingActionButton.extended(
label: Text('copy'),
onPressed:(){
Clipboard.setData(new ClipboardData(text: record.name));
_scaffoldKey.currentState.showSnackBar(SnackBar
(content: Text('text copied')));
}
)
```
|
3,911,433 |
I need to call a VB.NET DLL in VB6 application, does anybody have any ideas?
|
2010/10/12
|
[
"https://Stackoverflow.com/questions/3911433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/472874/"
] |
[How to call a Visual Basic .NET or Visual Basic 2005 assembly from Visual Basic 6.0](https://web.archive.org/web/20120210204121/http://support.microsoft.com/kb/817248)
[Using .NET DLL in VB6](https://www.codeproject.com/Articles/1194639/Using-NET-DLL-in-VB)
|
You can also export functions as standard windows DLL function entry points if you're willing to use a post compile tool
Check out
<http://www.codeproject.com/KB/dotnet/DllExport.aspx>
Works a treat and lets you integrate with all sorts of apps using Native VB.net when it'd require C or asm otherwise.
|
21,605,904 |
hi all i have gone through many thread and i found the way but don't know how to fit in my string please give me `regex`pattern to solve this.
```
input: String [200,350,500]
output: String{"200","350","500"}
```
one of the article where i found something:
[How to convert a String into an array of Strings containing one character each](https://stackoverflow.com/questions/1372599/how-to-convert-a-string-into-an-array-of-strings-containing-one-character-each)
|
2014/02/06
|
[
"https://Stackoverflow.com/questions/21605904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3154663/"
] |
Get the substring between the first and the last character and then split by `,`:
```
String input = "[200,350,500]";
String[] split = input.substring(1, input.length() - 1).split(",");
```
|
```
String input = "[200,350,500]";
String[] split = input.replaceAll("^.(.*).$","$1").split(",");
```
|
34,454,733 |
I'm having troubles scrawling a website that use Spanish characters. I wrote the following code to generate the codes the website uses for its leagues:
```
LEAGUES = ['Internacional', 'Inglaterra', 'España', 'Francia', 'Alemania', 'Italia', 'Holanda', 'Portugal', 'Australia',
'Bélgica', 'Egipto', 'Grecia', 'Omán', 'Irán', 'Japón', 'Kuwait', 'Marruecos', 'Arabia Saudí', 'Escocia', 'Turquía',
'Irlanda del Norte', 'Dinamarca', 'Rusia', 'Emiratos Árabes', 'Gales', 'Túnez', 'Noruega', 'Suecia', 'Argelia', 'Israel']
def codes_generator():
"""
generates dictionary containing codes for every division available
"""
codes = defaultdict(dict)
driver = selenium.webdriver.Chrome(executable_path='/media/Data.II/Dropbox/Projects/football-bidder/utils/chromedriver')
driver.get('https://www.miljugadas.com/es-ES/sportsbook')
driver.find_element_by_class_name('sport_240').click()
for league in LEAGUES:
try:
league = driver.find_element_by_link_text(league)
league.click()
except selenium.common.exceptions.NoSuchElementException as e:
continue
divisions = league.find_element_by_xpath("parent::*").find_elements_by_tag_name('li')
for division in divisions:
division = division.find_element_by_tag_name('a')
division_code = division.get_attribute('data-id')
division_name = division.text
codes[league.text][division_name] = division_code
return codes
{u'B\xe9lgica': {u'B\xe9lgica - Jupiler League': u'52995'}, u'Espa\xf1a': {u'Espa\xf1a - Liga BBVA': u'23170', u'Espa\xf1a - Copa del Rey': u'67954'}, u'Kuwait': {u'Kuwait \u2013 Liga': u'128783'}, u'Holanda': {u'Holanda - Eredivisie': u'47282'}, u'Irlanda del Norte': {u'Irlanda del Norte - Premier': u'57274'} u'Grecia': {u'Grecia - Super Liga': u'53509'}}
```
It returns a dictionary that is a pain to manage. I can't traverse leagues like the Spain which uses special spanish characters.
|
2015/12/24
|
[
"https://Stackoverflow.com/questions/34454733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3550480/"
] |
I had a similar problem, but with a duplication of computational graphs: they've just added in tensorboard when I called
```
writer.add_graph(graph=sess.graph)
```
In my case, it wasn't about log files but about Jupyter Notebook context.
I figured out that after multiple runs of a Jupyter cell with a Graph definition the graph hasn't been reset but appeared in the context as a duplicate, so I added
```
tf.reset_default_graph()
```
before the start of building a computational graph.
Hope it will help.
|
Add the following snippet to your code and it should automatically reset your tensorboard.
```
if tf.gfile.Exists(dirpath):
tf.gfile.DeleteRecursively(dirpath)
```
This will delete the previous logs.
|
34,454,733 |
I'm having troubles scrawling a website that use Spanish characters. I wrote the following code to generate the codes the website uses for its leagues:
```
LEAGUES = ['Internacional', 'Inglaterra', 'España', 'Francia', 'Alemania', 'Italia', 'Holanda', 'Portugal', 'Australia',
'Bélgica', 'Egipto', 'Grecia', 'Omán', 'Irán', 'Japón', 'Kuwait', 'Marruecos', 'Arabia Saudí', 'Escocia', 'Turquía',
'Irlanda del Norte', 'Dinamarca', 'Rusia', 'Emiratos Árabes', 'Gales', 'Túnez', 'Noruega', 'Suecia', 'Argelia', 'Israel']
def codes_generator():
"""
generates dictionary containing codes for every division available
"""
codes = defaultdict(dict)
driver = selenium.webdriver.Chrome(executable_path='/media/Data.II/Dropbox/Projects/football-bidder/utils/chromedriver')
driver.get('https://www.miljugadas.com/es-ES/sportsbook')
driver.find_element_by_class_name('sport_240').click()
for league in LEAGUES:
try:
league = driver.find_element_by_link_text(league)
league.click()
except selenium.common.exceptions.NoSuchElementException as e:
continue
divisions = league.find_element_by_xpath("parent::*").find_elements_by_tag_name('li')
for division in divisions:
division = division.find_element_by_tag_name('a')
division_code = division.get_attribute('data-id')
division_name = division.text
codes[league.text][division_name] = division_code
return codes
{u'B\xe9lgica': {u'B\xe9lgica - Jupiler League': u'52995'}, u'Espa\xf1a': {u'Espa\xf1a - Liga BBVA': u'23170', u'Espa\xf1a - Copa del Rey': u'67954'}, u'Kuwait': {u'Kuwait \u2013 Liga': u'128783'}, u'Holanda': {u'Holanda - Eredivisie': u'47282'}, u'Irlanda del Norte': {u'Irlanda del Norte - Premier': u'57274'} u'Grecia': {u'Grecia - Super Liga': u'53509'}}
```
It returns a dictionary that is a pain to manage. I can't traverse leagues like the Spain which uses special spanish characters.
|
2015/12/24
|
[
"https://Stackoverflow.com/questions/34454733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3550480/"
] |
I just figured out the solution to this problem. Just put each Events.out file in a separate folder inside your log directory. And you will get a nice visualization in tensorboard with each run in a different color.
|
Had a similar issue, which threw an error: '*You must feed a value for placeholder tensor 'dense\_input' with dtype float and shape*'. This specific issue was discussed [here](https://github.com/keras-team/keras/issues/10074).
The suggestion that worked for me used:
```
from keras.backend import clear_session
# Before instantiating a tf.data.Dataset obj & before model creation, call:
clear_session()
```
Also make sure you're using unique names for each model's TensorBoard log\_dir. Then to view all models, run TensorBoard from terminal at the parent dir of the logs files, I.e.:
```
tensorboard --logdir <projDir>/logs/tf_log
```
|
34,454,733 |
I'm having troubles scrawling a website that use Spanish characters. I wrote the following code to generate the codes the website uses for its leagues:
```
LEAGUES = ['Internacional', 'Inglaterra', 'España', 'Francia', 'Alemania', 'Italia', 'Holanda', 'Portugal', 'Australia',
'Bélgica', 'Egipto', 'Grecia', 'Omán', 'Irán', 'Japón', 'Kuwait', 'Marruecos', 'Arabia Saudí', 'Escocia', 'Turquía',
'Irlanda del Norte', 'Dinamarca', 'Rusia', 'Emiratos Árabes', 'Gales', 'Túnez', 'Noruega', 'Suecia', 'Argelia', 'Israel']
def codes_generator():
"""
generates dictionary containing codes for every division available
"""
codes = defaultdict(dict)
driver = selenium.webdriver.Chrome(executable_path='/media/Data.II/Dropbox/Projects/football-bidder/utils/chromedriver')
driver.get('https://www.miljugadas.com/es-ES/sportsbook')
driver.find_element_by_class_name('sport_240').click()
for league in LEAGUES:
try:
league = driver.find_element_by_link_text(league)
league.click()
except selenium.common.exceptions.NoSuchElementException as e:
continue
divisions = league.find_element_by_xpath("parent::*").find_elements_by_tag_name('li')
for division in divisions:
division = division.find_element_by_tag_name('a')
division_code = division.get_attribute('data-id')
division_name = division.text
codes[league.text][division_name] = division_code
return codes
{u'B\xe9lgica': {u'B\xe9lgica - Jupiler League': u'52995'}, u'Espa\xf1a': {u'Espa\xf1a - Liga BBVA': u'23170', u'Espa\xf1a - Copa del Rey': u'67954'}, u'Kuwait': {u'Kuwait \u2013 Liga': u'128783'}, u'Holanda': {u'Holanda - Eredivisie': u'47282'}, u'Irlanda del Norte': {u'Irlanda del Norte - Premier': u'57274'} u'Grecia': {u'Grecia - Super Liga': u'53509'}}
```
It returns a dictionary that is a pain to manage. I can't traverse leagues like the Spain which uses special spanish characters.
|
2015/12/24
|
[
"https://Stackoverflow.com/questions/34454733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3550480/"
] |
Yes, I believe ultimately this aspect is positive.
As an example, in my script I automate new run logs via `datetime`:
```py
from datetime import datetime
now = datetime.now()
logdir = "tf_logs/.../" + now.strftime("%Y%m%d-%H%M%S") + "/"
```
Then when running TensorBoard you can click the different runs on and off provided you ran TensorBoard in the parent directory.
If you **know** you don't care about a previous run and want it out of your life, then yes, you need to remove the event files and restart TensorBoard.
|
Add the following snippet to your code and it should automatically reset your tensorboard.
```
if tf.gfile.Exists(dirpath):
tf.gfile.DeleteRecursively(dirpath)
```
This will delete the previous logs.
|
34,454,733 |
I'm having troubles scrawling a website that use Spanish characters. I wrote the following code to generate the codes the website uses for its leagues:
```
LEAGUES = ['Internacional', 'Inglaterra', 'España', 'Francia', 'Alemania', 'Italia', 'Holanda', 'Portugal', 'Australia',
'Bélgica', 'Egipto', 'Grecia', 'Omán', 'Irán', 'Japón', 'Kuwait', 'Marruecos', 'Arabia Saudí', 'Escocia', 'Turquía',
'Irlanda del Norte', 'Dinamarca', 'Rusia', 'Emiratos Árabes', 'Gales', 'Túnez', 'Noruega', 'Suecia', 'Argelia', 'Israel']
def codes_generator():
"""
generates dictionary containing codes for every division available
"""
codes = defaultdict(dict)
driver = selenium.webdriver.Chrome(executable_path='/media/Data.II/Dropbox/Projects/football-bidder/utils/chromedriver')
driver.get('https://www.miljugadas.com/es-ES/sportsbook')
driver.find_element_by_class_name('sport_240').click()
for league in LEAGUES:
try:
league = driver.find_element_by_link_text(league)
league.click()
except selenium.common.exceptions.NoSuchElementException as e:
continue
divisions = league.find_element_by_xpath("parent::*").find_elements_by_tag_name('li')
for division in divisions:
division = division.find_element_by_tag_name('a')
division_code = division.get_attribute('data-id')
division_name = division.text
codes[league.text][division_name] = division_code
return codes
{u'B\xe9lgica': {u'B\xe9lgica - Jupiler League': u'52995'}, u'Espa\xf1a': {u'Espa\xf1a - Liga BBVA': u'23170', u'Espa\xf1a - Copa del Rey': u'67954'}, u'Kuwait': {u'Kuwait \u2013 Liga': u'128783'}, u'Holanda': {u'Holanda - Eredivisie': u'47282'}, u'Irlanda del Norte': {u'Irlanda del Norte - Premier': u'57274'} u'Grecia': {u'Grecia - Super Liga': u'53509'}}
```
It returns a dictionary that is a pain to manage. I can't traverse leagues like the Spain which uses special spanish characters.
|
2015/12/24
|
[
"https://Stackoverflow.com/questions/34454733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3550480/"
] |
Note: The solution you've posted (erase TensorBoard's log files and kill the process) will work, but it isn't preferred, because it destroys historical information about your training.
Instead, you can have each new training job write to a new subdirectory (of your top-level log directory). Then, TensorBoard will consider each job a new "run" and will create a nice comparison view so you can see how the training differed between iterations of your model.
In the following an example from <https://www.tensorflow.org/tensorboard/get_started>:
```
model = create_model()
...
model.compile(...)
log_dir = "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)
model.fit(..., callbacks=[tensorboard_callback])
```
|
I had a similar problem, but with a duplication of computational graphs: they've just added in tensorboard when I called
```
writer.add_graph(graph=sess.graph)
```
In my case, it wasn't about log files but about Jupyter Notebook context.
I figured out that after multiple runs of a Jupyter cell with a Graph definition the graph hasn't been reset but appeared in the context as a duplicate, so I added
```
tf.reset_default_graph()
```
before the start of building a computational graph.
Hope it will help.
|
34,454,733 |
I'm having troubles scrawling a website that use Spanish characters. I wrote the following code to generate the codes the website uses for its leagues:
```
LEAGUES = ['Internacional', 'Inglaterra', 'España', 'Francia', 'Alemania', 'Italia', 'Holanda', 'Portugal', 'Australia',
'Bélgica', 'Egipto', 'Grecia', 'Omán', 'Irán', 'Japón', 'Kuwait', 'Marruecos', 'Arabia Saudí', 'Escocia', 'Turquía',
'Irlanda del Norte', 'Dinamarca', 'Rusia', 'Emiratos Árabes', 'Gales', 'Túnez', 'Noruega', 'Suecia', 'Argelia', 'Israel']
def codes_generator():
"""
generates dictionary containing codes for every division available
"""
codes = defaultdict(dict)
driver = selenium.webdriver.Chrome(executable_path='/media/Data.II/Dropbox/Projects/football-bidder/utils/chromedriver')
driver.get('https://www.miljugadas.com/es-ES/sportsbook')
driver.find_element_by_class_name('sport_240').click()
for league in LEAGUES:
try:
league = driver.find_element_by_link_text(league)
league.click()
except selenium.common.exceptions.NoSuchElementException as e:
continue
divisions = league.find_element_by_xpath("parent::*").find_elements_by_tag_name('li')
for division in divisions:
division = division.find_element_by_tag_name('a')
division_code = division.get_attribute('data-id')
division_name = division.text
codes[league.text][division_name] = division_code
return codes
{u'B\xe9lgica': {u'B\xe9lgica - Jupiler League': u'52995'}, u'Espa\xf1a': {u'Espa\xf1a - Liga BBVA': u'23170', u'Espa\xf1a - Copa del Rey': u'67954'}, u'Kuwait': {u'Kuwait \u2013 Liga': u'128783'}, u'Holanda': {u'Holanda - Eredivisie': u'47282'}, u'Irlanda del Norte': {u'Irlanda del Norte - Premier': u'57274'} u'Grecia': {u'Grecia - Super Liga': u'53509'}}
```
It returns a dictionary that is a pain to manage. I can't traverse leagues like the Spain which uses special spanish characters.
|
2015/12/24
|
[
"https://Stackoverflow.com/questions/34454733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3550480/"
] |
Ok, for some reason it didn't work before but now it did:
**You must erase Tensorboard's log files AND kill its process**
After killing the process run `fuser 6006/tcp -k` to free port 6006 (if you're in linux) and fire tensorboard again.
|
Add the following snippet to your code and it should automatically reset your tensorboard.
```
if tf.gfile.Exists(dirpath):
tf.gfile.DeleteRecursively(dirpath)
```
This will delete the previous logs.
|
34,454,733 |
I'm having troubles scrawling a website that use Spanish characters. I wrote the following code to generate the codes the website uses for its leagues:
```
LEAGUES = ['Internacional', 'Inglaterra', 'España', 'Francia', 'Alemania', 'Italia', 'Holanda', 'Portugal', 'Australia',
'Bélgica', 'Egipto', 'Grecia', 'Omán', 'Irán', 'Japón', 'Kuwait', 'Marruecos', 'Arabia Saudí', 'Escocia', 'Turquía',
'Irlanda del Norte', 'Dinamarca', 'Rusia', 'Emiratos Árabes', 'Gales', 'Túnez', 'Noruega', 'Suecia', 'Argelia', 'Israel']
def codes_generator():
"""
generates dictionary containing codes for every division available
"""
codes = defaultdict(dict)
driver = selenium.webdriver.Chrome(executable_path='/media/Data.II/Dropbox/Projects/football-bidder/utils/chromedriver')
driver.get('https://www.miljugadas.com/es-ES/sportsbook')
driver.find_element_by_class_name('sport_240').click()
for league in LEAGUES:
try:
league = driver.find_element_by_link_text(league)
league.click()
except selenium.common.exceptions.NoSuchElementException as e:
continue
divisions = league.find_element_by_xpath("parent::*").find_elements_by_tag_name('li')
for division in divisions:
division = division.find_element_by_tag_name('a')
division_code = division.get_attribute('data-id')
division_name = division.text
codes[league.text][division_name] = division_code
return codes
{u'B\xe9lgica': {u'B\xe9lgica - Jupiler League': u'52995'}, u'Espa\xf1a': {u'Espa\xf1a - Liga BBVA': u'23170', u'Espa\xf1a - Copa del Rey': u'67954'}, u'Kuwait': {u'Kuwait \u2013 Liga': u'128783'}, u'Holanda': {u'Holanda - Eredivisie': u'47282'}, u'Irlanda del Norte': {u'Irlanda del Norte - Premier': u'57274'} u'Grecia': {u'Grecia - Super Liga': u'53509'}}
```
It returns a dictionary that is a pain to manage. I can't traverse leagues like the Spain which uses special spanish characters.
|
2015/12/24
|
[
"https://Stackoverflow.com/questions/34454733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3550480/"
] |
Note: The solution you've posted (erase TensorBoard's log files and kill the process) will work, but it isn't preferred, because it destroys historical information about your training.
Instead, you can have each new training job write to a new subdirectory (of your top-level log directory). Then, TensorBoard will consider each job a new "run" and will create a nice comparison view so you can see how the training differed between iterations of your model.
In the following an example from <https://www.tensorflow.org/tensorboard/get_started>:
```
model = create_model()
...
model.compile(...)
log_dir = "logs/fit/" + datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
tensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=1)
model.fit(..., callbacks=[tensorboard_callback])
```
|
Add the following snippet to your code and it should automatically reset your tensorboard.
```
if tf.gfile.Exists(dirpath):
tf.gfile.DeleteRecursively(dirpath)
```
This will delete the previous logs.
|
34,454,733 |
I'm having troubles scrawling a website that use Spanish characters. I wrote the following code to generate the codes the website uses for its leagues:
```
LEAGUES = ['Internacional', 'Inglaterra', 'España', 'Francia', 'Alemania', 'Italia', 'Holanda', 'Portugal', 'Australia',
'Bélgica', 'Egipto', 'Grecia', 'Omán', 'Irán', 'Japón', 'Kuwait', 'Marruecos', 'Arabia Saudí', 'Escocia', 'Turquía',
'Irlanda del Norte', 'Dinamarca', 'Rusia', 'Emiratos Árabes', 'Gales', 'Túnez', 'Noruega', 'Suecia', 'Argelia', 'Israel']
def codes_generator():
"""
generates dictionary containing codes for every division available
"""
codes = defaultdict(dict)
driver = selenium.webdriver.Chrome(executable_path='/media/Data.II/Dropbox/Projects/football-bidder/utils/chromedriver')
driver.get('https://www.miljugadas.com/es-ES/sportsbook')
driver.find_element_by_class_name('sport_240').click()
for league in LEAGUES:
try:
league = driver.find_element_by_link_text(league)
league.click()
except selenium.common.exceptions.NoSuchElementException as e:
continue
divisions = league.find_element_by_xpath("parent::*").find_elements_by_tag_name('li')
for division in divisions:
division = division.find_element_by_tag_name('a')
division_code = division.get_attribute('data-id')
division_name = division.text
codes[league.text][division_name] = division_code
return codes
{u'B\xe9lgica': {u'B\xe9lgica - Jupiler League': u'52995'}, u'Espa\xf1a': {u'Espa\xf1a - Liga BBVA': u'23170', u'Espa\xf1a - Copa del Rey': u'67954'}, u'Kuwait': {u'Kuwait \u2013 Liga': u'128783'}, u'Holanda': {u'Holanda - Eredivisie': u'47282'}, u'Irlanda del Norte': {u'Irlanda del Norte - Premier': u'57274'} u'Grecia': {u'Grecia - Super Liga': u'53509'}}
```
It returns a dictionary that is a pain to manage. I can't traverse leagues like the Spain which uses special spanish characters.
|
2015/12/24
|
[
"https://Stackoverflow.com/questions/34454733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3550480/"
] |
Had a similar issue, which threw an error: '*You must feed a value for placeholder tensor 'dense\_input' with dtype float and shape*'. This specific issue was discussed [here](https://github.com/keras-team/keras/issues/10074).
The suggestion that worked for me used:
```
from keras.backend import clear_session
# Before instantiating a tf.data.Dataset obj & before model creation, call:
clear_session()
```
Also make sure you're using unique names for each model's TensorBoard log\_dir. Then to view all models, run TensorBoard from terminal at the parent dir of the logs files, I.e.:
```
tensorboard --logdir <projDir>/logs/tf_log
```
|
This automatically deletes the log directory.
```
import shutil
shutil.rmtree('log_dir', ignore_errors=True)
```
|
34,454,733 |
I'm having troubles scrawling a website that use Spanish characters. I wrote the following code to generate the codes the website uses for its leagues:
```
LEAGUES = ['Internacional', 'Inglaterra', 'España', 'Francia', 'Alemania', 'Italia', 'Holanda', 'Portugal', 'Australia',
'Bélgica', 'Egipto', 'Grecia', 'Omán', 'Irán', 'Japón', 'Kuwait', 'Marruecos', 'Arabia Saudí', 'Escocia', 'Turquía',
'Irlanda del Norte', 'Dinamarca', 'Rusia', 'Emiratos Árabes', 'Gales', 'Túnez', 'Noruega', 'Suecia', 'Argelia', 'Israel']
def codes_generator():
"""
generates dictionary containing codes for every division available
"""
codes = defaultdict(dict)
driver = selenium.webdriver.Chrome(executable_path='/media/Data.II/Dropbox/Projects/football-bidder/utils/chromedriver')
driver.get('https://www.miljugadas.com/es-ES/sportsbook')
driver.find_element_by_class_name('sport_240').click()
for league in LEAGUES:
try:
league = driver.find_element_by_link_text(league)
league.click()
except selenium.common.exceptions.NoSuchElementException as e:
continue
divisions = league.find_element_by_xpath("parent::*").find_elements_by_tag_name('li')
for division in divisions:
division = division.find_element_by_tag_name('a')
division_code = division.get_attribute('data-id')
division_name = division.text
codes[league.text][division_name] = division_code
return codes
{u'B\xe9lgica': {u'B\xe9lgica - Jupiler League': u'52995'}, u'Espa\xf1a': {u'Espa\xf1a - Liga BBVA': u'23170', u'Espa\xf1a - Copa del Rey': u'67954'}, u'Kuwait': {u'Kuwait \u2013 Liga': u'128783'}, u'Holanda': {u'Holanda - Eredivisie': u'47282'}, u'Irlanda del Norte': {u'Irlanda del Norte - Premier': u'57274'} u'Grecia': {u'Grecia - Super Liga': u'53509'}}
```
It returns a dictionary that is a pain to manage. I can't traverse leagues like the Spain which uses special spanish characters.
|
2015/12/24
|
[
"https://Stackoverflow.com/questions/34454733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3550480/"
] |
I just figured out the solution to this problem. Just put each Events.out file in a separate folder inside your log directory. And you will get a nice visualization in tensorboard with each run in a different color.
|
Add the following snippet to your code and it should automatically reset your tensorboard.
```
if tf.gfile.Exists(dirpath):
tf.gfile.DeleteRecursively(dirpath)
```
This will delete the previous logs.
|
34,454,733 |
I'm having troubles scrawling a website that use Spanish characters. I wrote the following code to generate the codes the website uses for its leagues:
```
LEAGUES = ['Internacional', 'Inglaterra', 'España', 'Francia', 'Alemania', 'Italia', 'Holanda', 'Portugal', 'Australia',
'Bélgica', 'Egipto', 'Grecia', 'Omán', 'Irán', 'Japón', 'Kuwait', 'Marruecos', 'Arabia Saudí', 'Escocia', 'Turquía',
'Irlanda del Norte', 'Dinamarca', 'Rusia', 'Emiratos Árabes', 'Gales', 'Túnez', 'Noruega', 'Suecia', 'Argelia', 'Israel']
def codes_generator():
"""
generates dictionary containing codes for every division available
"""
codes = defaultdict(dict)
driver = selenium.webdriver.Chrome(executable_path='/media/Data.II/Dropbox/Projects/football-bidder/utils/chromedriver')
driver.get('https://www.miljugadas.com/es-ES/sportsbook')
driver.find_element_by_class_name('sport_240').click()
for league in LEAGUES:
try:
league = driver.find_element_by_link_text(league)
league.click()
except selenium.common.exceptions.NoSuchElementException as e:
continue
divisions = league.find_element_by_xpath("parent::*").find_elements_by_tag_name('li')
for division in divisions:
division = division.find_element_by_tag_name('a')
division_code = division.get_attribute('data-id')
division_name = division.text
codes[league.text][division_name] = division_code
return codes
{u'B\xe9lgica': {u'B\xe9lgica - Jupiler League': u'52995'}, u'Espa\xf1a': {u'Espa\xf1a - Liga BBVA': u'23170', u'Espa\xf1a - Copa del Rey': u'67954'}, u'Kuwait': {u'Kuwait \u2013 Liga': u'128783'}, u'Holanda': {u'Holanda - Eredivisie': u'47282'}, u'Irlanda del Norte': {u'Irlanda del Norte - Premier': u'57274'} u'Grecia': {u'Grecia - Super Liga': u'53509'}}
```
It returns a dictionary that is a pain to manage. I can't traverse leagues like the Spain which uses special spanish characters.
|
2015/12/24
|
[
"https://Stackoverflow.com/questions/34454733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3550480/"
] |
Yes, I believe ultimately this aspect is positive.
As an example, in my script I automate new run logs via `datetime`:
```py
from datetime import datetime
now = datetime.now()
logdir = "tf_logs/.../" + now.strftime("%Y%m%d-%H%M%S") + "/"
```
Then when running TensorBoard you can click the different runs on and off provided you ran TensorBoard in the parent directory.
If you **know** you don't care about a previous run and want it out of your life, then yes, you need to remove the event files and restart TensorBoard.
|
This automatically deletes the log directory.
```
import shutil
shutil.rmtree('log_dir', ignore_errors=True)
```
|
34,454,733 |
I'm having troubles scrawling a website that use Spanish characters. I wrote the following code to generate the codes the website uses for its leagues:
```
LEAGUES = ['Internacional', 'Inglaterra', 'España', 'Francia', 'Alemania', 'Italia', 'Holanda', 'Portugal', 'Australia',
'Bélgica', 'Egipto', 'Grecia', 'Omán', 'Irán', 'Japón', 'Kuwait', 'Marruecos', 'Arabia Saudí', 'Escocia', 'Turquía',
'Irlanda del Norte', 'Dinamarca', 'Rusia', 'Emiratos Árabes', 'Gales', 'Túnez', 'Noruega', 'Suecia', 'Argelia', 'Israel']
def codes_generator():
"""
generates dictionary containing codes for every division available
"""
codes = defaultdict(dict)
driver = selenium.webdriver.Chrome(executable_path='/media/Data.II/Dropbox/Projects/football-bidder/utils/chromedriver')
driver.get('https://www.miljugadas.com/es-ES/sportsbook')
driver.find_element_by_class_name('sport_240').click()
for league in LEAGUES:
try:
league = driver.find_element_by_link_text(league)
league.click()
except selenium.common.exceptions.NoSuchElementException as e:
continue
divisions = league.find_element_by_xpath("parent::*").find_elements_by_tag_name('li')
for division in divisions:
division = division.find_element_by_tag_name('a')
division_code = division.get_attribute('data-id')
division_name = division.text
codes[league.text][division_name] = division_code
return codes
{u'B\xe9lgica': {u'B\xe9lgica - Jupiler League': u'52995'}, u'Espa\xf1a': {u'Espa\xf1a - Liga BBVA': u'23170', u'Espa\xf1a - Copa del Rey': u'67954'}, u'Kuwait': {u'Kuwait \u2013 Liga': u'128783'}, u'Holanda': {u'Holanda - Eredivisie': u'47282'}, u'Irlanda del Norte': {u'Irlanda del Norte - Premier': u'57274'} u'Grecia': {u'Grecia - Super Liga': u'53509'}}
```
It returns a dictionary that is a pain to manage. I can't traverse leagues like the Spain which uses special spanish characters.
|
2015/12/24
|
[
"https://Stackoverflow.com/questions/34454733",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3550480/"
] |
I had a similar problem, but with a duplication of computational graphs: they've just added in tensorboard when I called
```
writer.add_graph(graph=sess.graph)
```
In my case, it wasn't about log files but about Jupyter Notebook context.
I figured out that after multiple runs of a Jupyter cell with a Graph definition the graph hasn't been reset but appeared in the context as a duplicate, so I added
```
tf.reset_default_graph()
```
before the start of building a computational graph.
Hope it will help.
|
This automatically deletes the log directory.
```
import shutil
shutil.rmtree('log_dir', ignore_errors=True)
```
|
2,285,692 |
Is there a way to prove that every Riemann integrable function is a uniform limit of step functions? If not, does there exist a function that contradicts this?
|
2017/05/17
|
[
"https://math.stackexchange.com/questions/2285692",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/421156/"
] |
The above suggested counterexample doesn't actually work, since that choice of $f(x)$ is itself a step function, namely the indicator function of $[1,1]$. Thus, the trivial sequence of functions $f\_n(x)=f(x)$ is a sequence of step functions uniformely convergent to $f(x)$ and they are all indeed Riemann integrable.
Instead, a valid counterexample could be $\space f(x):[0,1] \rightarrow \mathbb{R}$ given by $f(x)=1$ if $x=\frac{1}{2^n}$ and $f(x)=0$ otherwise. This function is Riemann integrable and has integral equal to zero; nonetheless, there is no sequence of step functions which converges to it uniformly.
To prove that $f(x)$ is Riemann integrable just take the constant step function $\phi\_{-}(x)=0$ as a minorant and e.g. the sequence of functions $\phi\_{{n}\_{+}}(x)=1 $ for $ x<\frac{1}{n}$ and $\phi\_{{n}\_{+}}(x)=f(x)$ otherwise as majorants, the integral of which tends to zero.
To prove that there is no sequence of step functions uniformly converging to it, note that any step function $\phi\_n$ must be constant in some interval $(0, \delta\_n)$ with $\delta\_n>0$, so $\space \phi\_n(x)=k\_n$ for $x \in (0, \delta\_n)$. $\space$ For any $\delta\_n$ there is $N$ such that $a\_n=\frac{1}{2^N} $ and $b\_n=\frac{3}{2^{N+2}}\in (0, \delta\_n)$ and $f(a\_n)=1$,$ \space f(b\_n)=0$.
By observing that either $|k\_n-f(a\_n)|=|k\_n-1| \geqslant \frac{1}{2}$ or $|k\_n-f(b\_n)|=|k\_n| \geqslant \frac{1}{2}$ obtains, we deduce that $sup\_{x\in [0,1]}|\phi\_n(x)-f(x)| \geqslant sup\_{x\in (0, \delta\_n)}|\phi\_n(x)-f(x)| \geqslant \frac{1}{2} \neq 0$.
Therefore, no sequence of step functions can converge uniformly to $f$ on $[0,1]$ given that for any step function $\space sup\_{x\in [0,1]}|\phi\_n(x)-f(x)| \geqslant \frac{1}{2}$.
|
Take as a counterexample,
$$f(x) = \begin{cases} 0, \,\, 0 \leqslant x < 1 \\ 1, \,\, x = 1 \\ 0, \,\, 1 < x \leqslant 2 \end{cases}$$
There exist sequences of step functions converging pointwise to $f$ -- for example
$$s\_n(x) = \begin{cases} 0, \,\, 0 \leqslant x < 1-1/n \\ 1, \,\, 1- 1/n \leqslant x \leqslant 1 + 1/n \\ 0, \,\, 1+ 1/n < x \leqslant 2 \end{cases}$$
However, no such sequence $(s\_n)$ can converge uniformly. For any $n \in \mathbf{N}$, the step function $s\_n$ assumes constant values on intervals. If the interval $I\_n$ where $s\_n(x) = c\_n$ includes $x= 1$, then $|f(1) - s\_n(1)| = |1 - c\_n|$ but there is some other point $x \in I\_n$ where $|f(x) - s\_n(x)| = |c\_n|$.
Show that no matter how $c\_n$ is chosen, given say $\epsilon =1/4$, we cannot have both $|1 - c\_n| < \epsilon$ and $|c\_n| < \epsilon$.
|
193,304 |
I recently purchased a 1/2" garden hose and two hose fittings (not native English speaker, this is what the English version of the store's website calls them - image attached) which according to the packaging are for 1/2".
The problem is that the hose is really difficult to connect to the fittings, it's a really tight fit, and I can only get the horse pushed about 5mm over the connector. This is barely enough for the locking mechanism to be able to press against the hose, but when the water is turned on one of the fittings eventually comes lose. I assume I need to push the hose further over the connector.
I've tried to use WD-40 to lubricate the hose and connector, but it didn't really seem to help. I also tried to expand the hose by using pilers, but that didn't really work.
Any ideas?
[Here's an image of the hose fitting from the shop's website](https://productimages.biltema.com/v1/image/imagebyfilename/14-014_xxl_1.jpg)
|
2020/05/21
|
[
"https://diy.stackexchange.com/questions/193304",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/117555/"
] |
This is possibly a daft question, but just to be sure - you are unscrewing the "nut" that is on the right side of that picture, sliding that over the hose, pushing the hose under the "fingers", and then doing the nut back up?
If so, and you're sure that that hose and fitting are the same size, then try putting the end of the hose in a bucket of hot water for 15 minutes. It should soften the hose enough to allow you to wiggle it all the way into the connector, and then do the nut up.
Edit: as they say a picture is worth a thousand words. This clearly shows what I'm trying to explain.
<https://www.youtube.com/watch?v=HR8OkhLhtYo>
|
I ran into this same problem a few times and the fix was to replace the hose. My last problem was with a 5/8" hose and a 5/8" repair end . No matter what I did I could not get any repair end to fit that hose so the rubbish man received it when he collected the trash.
|
1,962,004 |
I have to solve a couple of problems involving very large numbers, ie. those that are too big to use in a calculator. I clearly need a general approach for this sort of problem. Any pointers would be appreciated, ie. no need to solve the problems completely, just give me some direction. (If I get desperate I'll ask for actual solutions :)
The two problems are:
1) Is $2222^{5555} + 5555^{2222}$ prime?
and
2) Can you demonstrate that the digital representation of $7^{35}$ contains at least one digit that occurs four times?
Based on a hint from Chas, I have an idea for (2).
For a number to contain one digit four times, it must have at least 31 digits. That is, a 30-digit number may not meet the criterion as it could have each of the ten digits 3 times. But as soon as we have 31-digits, a fourth occurrence of one of the digits must be present.
Therefore we meet the criterion if:
\begin{align}
7^{35} &> 10^{30} \\
log(7^{35}) &> log(10^{30}) \\
35 \*log(7) &> 30 \* log(10) \\
35 \* 0.845 &> 30 \\
29.58 &> 30
\end{align}
The inequality is not true. Therefore I cannot prove the criterion can be met. Am I on the right track?
|
2016/10/10
|
[
"https://math.stackexchange.com/questions/1962004",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/272669/"
] |
For Question 1, you can easily prove it is not prime by considering that both 5555 and 2222 are divisible by 1111
Continuing your proof on question 2:
You have shown correctly that $7^{35}$ has exactly 30 digits and that it is not enough to say there is at least one digit that repeats 4 times. By pigeon hole, the only time when this happens is when all the 10 digits repeat 3 times. So in this case, when we take the sum of the digits, it is a multiple of 3, and hence the number is divisible by 3.This is not possible has $7^{35}$ is not a multiple of 3. Thereby, we have proved that this case is not possible
|
Hint for the first question:
What is $2222^{5555} \mod 3$? What is $5555^{2222} \mod 3$?
Hint for the second question:
How many digits long is $7^{35}$?
|
31,240,952 |
I just upgraded to `pymongo==3.0.3` via `pip install --upgrade pymongo`, and I'm flooded with `ImportError`:
```py
In [2]: pymongo.version
Out[2]: '3.0.3'
In [3]: from pymongo import Connection
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-3-dd44bc3249d3> in <module>()
----> 1 from pymongo import Connection
ImportError: cannot import name Connection
In [4]: from pymongo import connection
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-4-71c9e4ec1bcd> in <module>()
----> 1 from pymongo import connection
ImportError: cannot import name connection
In [5]: import pymongo.connection.Connection
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-5-282b89157c85> in <module>()
----> 1 import pymongo.connection.Connection
ImportError: No module named connection.Connection
```
|
2015/07/06
|
[
"https://Stackoverflow.com/questions/31240952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2810981/"
] |
According to [Pymongo 3.0 changelog](http://api.mongodb.org/python/current/changelog.html#mongoclient-changes) -
>
> **MongoClient changes**
>
>
> MongoClient is now the one and only client class for a standalone server, mongos, or replica set. It includes the functionality that had been split into MongoReplicaSetClient: it can connect to a replica set, discover all its members, and monitor the set for stepdowns, elections, and reconfigs. MongoClient now also supports the full ReadPreference API.
>
>
> The obsolete classes MasterSlaveConnection, Connection, and ReplicaSetConnection are removed.
>
>
>
As you can see Connection class has been removed from pymonge 3.0 , try using MongoClient instead. Information about mongoclient can be found [here](http://api.mongodb.org/python/current/api/pymongo/mongo_client.html#pymongo.mongo_client.MongoClient)
|
Probably you can support both versions in your code by doing something like this.
```
try:
from pymongo.connection import Connection
except ImportError as e:
from pymongo import MongoClient as Connection
```
|
31,240,952 |
I just upgraded to `pymongo==3.0.3` via `pip install --upgrade pymongo`, and I'm flooded with `ImportError`:
```py
In [2]: pymongo.version
Out[2]: '3.0.3'
In [3]: from pymongo import Connection
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-3-dd44bc3249d3> in <module>()
----> 1 from pymongo import Connection
ImportError: cannot import name Connection
In [4]: from pymongo import connection
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-4-71c9e4ec1bcd> in <module>()
----> 1 from pymongo import connection
ImportError: cannot import name connection
In [5]: import pymongo.connection.Connection
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
<ipython-input-5-282b89157c85> in <module>()
----> 1 import pymongo.connection.Connection
ImportError: No module named connection.Connection
```
|
2015/07/06
|
[
"https://Stackoverflow.com/questions/31240952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2810981/"
] |
According to [Pymongo 3.0 changelog](http://api.mongodb.org/python/current/changelog.html#mongoclient-changes) -
>
> **MongoClient changes**
>
>
> MongoClient is now the one and only client class for a standalone server, mongos, or replica set. It includes the functionality that had been split into MongoReplicaSetClient: it can connect to a replica set, discover all its members, and monitor the set for stepdowns, elections, and reconfigs. MongoClient now also supports the full ReadPreference API.
>
>
> The obsolete classes MasterSlaveConnection, Connection, and ReplicaSetConnection are removed.
>
>
>
As you can see Connection class has been removed from pymonge 3.0 , try using MongoClient instead. Information about mongoclient can be found [here](http://api.mongodb.org/python/current/api/pymongo/mongo_client.html#pymongo.mongo_client.MongoClient)
|
Since Connection class is deprecated from pymongo(3.0.0). Install a older version of pymongo(2.9) to make it temporarily work. It can be done with pip using:
```
pip install pymongo==2.9
```
|
47,249,699 |
I write a boot loader in asm and want to add some compiled C code in my project.
I created a test function here:
**test.c**
```
__asm__(".code16\n");
void print_str() {
__asm__ __volatile__("mov $'A' , %al\n");
__asm__ __volatile__("mov $0x0e, %ah\n");
__asm__ __volatile__("int $0x10\n");
}
```
And here is the asm code (the boot loader):
**hw.asm**
```
[org 0x7C00]
[BITS 16]
[extern print_str] ;nasm tip
start:
mov ax, 0
mov ds, ax
mov es, ax
mov ss, ax
mov sp, 0x7C00
mov si, name
call print_string
mov al, ' '
int 10h
mov si, version
call print_string
mov si, line_return
call print_string
call print_str ;call function
mov si, welcome
call print_string
jmp mainloop
mainloop:
mov si, prompt
call print_string
mov di, buffer
call get_str
mov si, buffer
cmp byte [si], 0
je mainloop
mov si, buffer
;call print_string
mov di, cmd_version
call strcmp
jc .version
jmp mainloop
.version:
mov si, name
call print_string
mov al, ' '
int 10h
mov si, version
call print_string
mov si, line_return
call print_string
jmp mainloop
name db 'MOS', 0
version db 'v0.1', 0
welcome db 'Developped by Marius Van Nieuwenhuyse', 0x0D, 0x0A, 0
prompt db '>', 0
line_return db 0x0D, 0x0A, 0
buffer times 64 db 0
cmd_version db 'version', 0
%include "functions/print.asm"
%include "functions/getstr.asm"
%include "functions/strcmp.asm"
times 510 - ($-$$) db 0
dw 0xaa55
```
I need to call the c function like a simple asm function
Without the extern and the call `print_str`, the asm script boot in VMWare.
I tried to compile with:
```
nasm -f elf32
```
***But i can't call org 0x7C00***
|
2017/11/12
|
[
"https://Stackoverflow.com/questions/47249699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5562200/"
] |
>
> I write a boot loader in asm and want to add some compiled C code in my project.
>
>
>
Then you need to use a 16-bit x86 compiler, such as [OpenWatcom](http://www.openwatcom.org/).
**GCC cannot safely build real-mode code**, as it is unaware of some important features of the platform, including memory segmentation. Inserting the `.code16` directive will make the compiler generate incorrect output. Despite appearing in many tutorials, this piece of advice is simply incorrect, and should not be used.
|
First i want to express how to link C compiled code with assembled file.
I put together some Q/A in SO and reach to this.
***C code:***
**func.c**
```
//__asm__(".code16gcc\n");when we use eax, 32 bit reg we cant use this as truncate
//problem
#include <stdio.h>
int x = 0;
int madd(int a, int b)
{
return a + b;
}
void mexit(){
__asm__ __volatile__("mov $0, %ebx\n");
__asm__ __volatile__("mov $1, %eax \n");
__asm__ __volatile__("int $0x80\n");
}
char* tmp;
///how to direct use of arguments in asm command
void print_str(int a, char* s){
x = a;
__asm__("mov x, %edx\n");// ;third argument: message length
tmp = s;
__asm__("mov tmp, %ecx\n");// ;second argument: pointer to message to write
__asm__("mov $1, %ebx\n");//first argument: file handle (stdout)
__asm__("mov $4, %eax\n");//system call number (sys_write)
__asm__ __volatile__("int $0x80\n");//call kernel
}
void mtest(){
printf("%s\n", "Hi");
//putchar('a');//why not work
}
///gcc -c func.c -o func
```
***Assembly code:***
**hello.asm**
```
extern mtest
extern printf
extern putchar
extern print_str
extern mexit
extern madd
section .text ;section declaration
;we must export the entry point to the ELF linker or
global _start ;loader. They conventionally recognize _start as their
;entry point. Use ld -e foo to override the default.
_start:
;write our string to stdout
push msg
push len
call print_str;
call mtest ;print "Hi"; call printf inside a void function
; use add inside func.c
push 5
push 10
call madd;
;direct call of <stdio.h> printf()
push eax
push format
call printf; ;printf(format, eax)
call mexit; ;exit to OS
section .data ;section declaration
format db "%d", 10, 0
msg db "Hello, world!",0xa ;our dear string
len equ $ - msg ;length of our dear string
; nasm -f elf32 hello.asm -o hello
;Link two files
;ld hello func -o hl -lc -I /lib/ld-linux.so.2
; ./hl run code
;chain to assemble, compile, Run
;; gcc -c func.c -o func && nasm -f elf32 hello.asm -o hello && ld hello func -o hl -lc -I /lib/ld-linux.so.2 && echo &&./hl
```
***Chain commands for assemble, compile and Run***
>
> `gcc -c func.c -o func && nasm -f elf32 hello.asm -o hello && ld hello func -o hl -lc -I /lib/ld-linux.so.2 && echo && ./hl`
>
>
>
***Edit[toDO]***
* Write boot loader code instead of this version
* Some explanation on how ld, gcc, nasm works.
|
47,249,699 |
I write a boot loader in asm and want to add some compiled C code in my project.
I created a test function here:
**test.c**
```
__asm__(".code16\n");
void print_str() {
__asm__ __volatile__("mov $'A' , %al\n");
__asm__ __volatile__("mov $0x0e, %ah\n");
__asm__ __volatile__("int $0x10\n");
}
```
And here is the asm code (the boot loader):
**hw.asm**
```
[org 0x7C00]
[BITS 16]
[extern print_str] ;nasm tip
start:
mov ax, 0
mov ds, ax
mov es, ax
mov ss, ax
mov sp, 0x7C00
mov si, name
call print_string
mov al, ' '
int 10h
mov si, version
call print_string
mov si, line_return
call print_string
call print_str ;call function
mov si, welcome
call print_string
jmp mainloop
mainloop:
mov si, prompt
call print_string
mov di, buffer
call get_str
mov si, buffer
cmp byte [si], 0
je mainloop
mov si, buffer
;call print_string
mov di, cmd_version
call strcmp
jc .version
jmp mainloop
.version:
mov si, name
call print_string
mov al, ' '
int 10h
mov si, version
call print_string
mov si, line_return
call print_string
jmp mainloop
name db 'MOS', 0
version db 'v0.1', 0
welcome db 'Developped by Marius Van Nieuwenhuyse', 0x0D, 0x0A, 0
prompt db '>', 0
line_return db 0x0D, 0x0A, 0
buffer times 64 db 0
cmd_version db 'version', 0
%include "functions/print.asm"
%include "functions/getstr.asm"
%include "functions/strcmp.asm"
times 510 - ($-$$) db 0
dw 0xaa55
```
I need to call the c function like a simple asm function
Without the extern and the call `print_str`, the asm script boot in VMWare.
I tried to compile with:
```
nasm -f elf32
```
***But i can't call org 0x7C00***
|
2017/11/12
|
[
"https://Stackoverflow.com/questions/47249699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5562200/"
] |
Compiling & Linking NASM and GCC Code
-------------------------------------
This question has a more complex answer than one might believe, although it is possible. Can the first stage of a bootloader (the original 512 bytes that get loaded at physical address 0x07c00) make a call into a *C* function? Yes, but it requires rethinking how you build your project.
For this to work you can no longer us `-f bin` with *NASM*. This also means you can't use the `org 0x7c00` to tell the assembler what address the code expects to start from. You'll need to do this through a linker (either us *LD* directly or *GCC* for linking). Since the linker will lay things out in memory we can't rely on placing the boot sector signature `0xaa55` in our output file. We can get the linker to do that for us.
The first problem you will discover is that the default linker scripts used internally by *GCC* don't lay things out the way we want. We'll need to create our own. Such a linker script will have to set the origin point (Virtual Memory Address aka VMA) to 0x7c00, place the code from your assembly file before the data and place the boot signature at offset 510 in the file. I'm not going to write a tutorial on Linker scripts. The [Binutils Documentation](https://sourceware.org/binutils/docs/ld/Scripts.html#Scripts) contains almost everything you need to know about linker scripts.
```
OUTPUT_FORMAT("elf32-i386");
/* We define an entry point to keep the linker quiet. This entry point
* has no meaning with a bootloader in the binary image we will eventually
* generate. Bootloader will start executing at whatever is at 0x07c00 */
ENTRY(start);
SECTIONS
{
. = 0x7C00;
.text : {
/* Place the code in hw.o before all other code */
hw.o(.text);
*(.text);
}
/* Place the data after the code */
.data : SUBALIGN(2) {
*(.data);
*(.rodata*);
}
/* Place the boot signature at LMA/VMA 0x7DFE */
.sig 0x7DFE : {
SHORT(0xaa55);
}
/* Place the uninitialised data in the area after our bootloader
* The BIOS only reads the 512 bytes before this into memory */
.bss : SUBALIGN(4) {
__bss_start = .;
*(COMMON);
*(.bss)
. = ALIGN(4);
__bss_end = .;
}
__bss_sizeb = SIZEOF(.bss);
/* Remove sections that won't be relevant to us */
/DISCARD/ : {
*(.eh_frame);
*(.comment);
}
}
```
This script should create an *ELF* executable that can be converted to a flat binary file with *OBJCOPY*. We could have output as a binary file directly but I separate the two processes out in the event I want to include debug information in the *ELF* version for debug purposes.
Now that we have a linker script we must remove the `ORG 0x7c00` and the boot signature. For simplicity sake we'll try to get the following code (`hw.asm`) to work:
```
extern print_str
global start
bits 16
section .text
start:
xor ax, ax ; AX = 0
mov ds, ax
mov es, ax
mov ss, ax
mov sp, 0x7C00
call print_str ; call function
/* Halt the processor so we don't keep executing code beyond this point */
cli
hlt
```
You can include all your other code, but this sample will still demonstrate the basics of calling into a *C* function.
Assume the code above you can now generate the *ELF* object from `hw.asm` producing `hw.o` using this command:
```
nasm -f elf32 hw.asm -o hw.o
```
You compile each *C* file with something like:
```
gcc -ffreestanding -c kmain.c -o kmain.o
```
I placed the *C* code you had into a file called `kmain.c` . The command above will generate `kmain.o`. I noticed you aren't using a cross compiler so you'll want to use `-fno-PIE` to ensure we don't generate relocatable code. `-ffreestanding` tells GCC the *C* standard library may not exist, and `main` may not be the program entry point. You'd compile each *C* file in the same way.
To link this code to a final executable and then produce a flat binary file that can be booted we do this:
```
ld -melf_i386 --build-id=none -T link.ld kmain.o hw.o -o kernel.elf
objcopy -O binary kernel.elf kernel.bin
```
You specify all the object files to link with the *LD* command. The *LD* command above will produce a 32-bit ELF executable called `kernel.elf`. This file can be useful in the future for debugging purposes. Here we use *OBJCOPY* to convert `kernel.elf` to a binary file called `kernel.bin`. `kernel.bin` can be used as a bootloader image.
You should be able to run it with *QEMU* using this command:
```
qemu-system-i386 -fda kernel.bin
```
When run it may look like:
[](https://i.stack.imgur.com/IIXKl.png)
You'll notice the letter `A` appears on the last line. This is what we'd expect from the `print_str` code.
---
GCC Inline Assembly is Hard to Get Right
----------------------------------------
If we take your example code in the question:
```
__asm__ __volatile__("mov $'A' , %al\n");
__asm__ __volatile__("mov $0x0e, %ah\n");
__asm__ __volatile__("int $0x10\n");
```
The compiler is free to reorder these `__asm__` statements if it wanted to. The `int $0x10` could appear before the MOV instructions. If you want these 3 lines to be output in this exact order you can combine them into one like this:
```
__asm__ __volatile__("mov $'A' , %al\n\t"
"mov $0x0e, %ah\n\t"
"int $0x10");
```
These are basic assembly statements. It's not required to specify `__volatile__`on them as they are already [implicitly volatile](https://gcc.gnu.org/onlinedocs/gcc/Basic-Asm.html#Basic-Asm), so it has no effect. From the original poster's answer it is clear they want to eventually use variables in `__asm__` blocks. This is doable with [extended inline assembly](https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#Extended-Asm) (the instruction string is followed by a colon `:` followed by constraints.):
With extended asm you can read and write C variables from assembler and perform jumps from assembler code to C labels. Extended asm syntax uses colons (‘:’) to delimit the operand parameters after the assembler template:
>
>
> ```
> asm [volatile] ( AssemblerTemplate
> : OutputOperands
> [ : InputOperands
> [ : Clobbers ] ])
>
> ```
>
>
This answer isn't a tutorial on inline assembly. The general rule of thumb is that one [should not use inline assembly unless you have to](https://gcc.gnu.org/wiki/DontUseInlineAsm). Inline assembly done wrong can create hard to track bugs or have unusual side effects. Unfortunately doing 16-bit interrupts in *C* pretty much requires it, or you write the entire function in assembly (ie: NASM).
This is an example of a `print_chr` function that take a nul terminated string and prints each character out one by one using [Int 10h/ah=0ah](http://www.ctyme.com/intr/rb-0106.htm):
```
#include <stdint.h>
__asm__(".code16gcc\n");
void print_str(char *str) {
while (*str) {
/* AH=0x0e, AL=char to print, BH=page, BL=fg color */
__asm__ __volatile__ ("int $0x10"
:
: "a" ((0x0e<<8) | *str++),
"b" (0x0000));
}
}
```
`hw.asm` would be modified to look like this:
```
push welcome
call print_str ;call function
```
The idea when this is assembled/compiled (using the commands in the first section of this answer) and run is that it print out the `welcome` message. Unfortunately it will almost never work, and may even crash some emulators like *QEMU*.
---
code16 is Almost Useless and Should Not be Used
-----------------------------------------------
In the last section we learn that a simple function that takes a parameter ends up not working and may even crash an emulator like *QEMU*. The main problem is that the `__asm__(".code16\n");` statement really doesn't work well with the code generated by *GCC*. The [Binutils AS documentation](https://sourceware.org/binutils/docs/as/i386_002d16bit.html) says:
>
> ‘.code16gcc’ provides experimental support for generating 16-bit code from gcc, and differs from ‘.code16’ in that ‘call’, ‘ret’, ‘enter’, ‘leave’, ‘push’, ‘pop’, ‘pusha’, ‘popa’, ‘pushf’, and ‘popf’ instructions default to 32-bit size. This is so that the stack pointer is manipulated in the same way over function calls, allowing access to function parameters at the same stack offsets as in 32-bit mode. ‘.code16gcc’ also automatically adds address size prefixes where necessary to use the 32-bit addressing modes that gcc generates.
>
>
>
`.code16gcc` is what you really need to be using, not `.code16`. This force GNU assembler on the back end to emit address and operand prefixes on certain instructions so that the addresses and operands are treated as 4 bytes wide, and not 2 bytes.
The hand written code in *NASM* doesn't know it will be calling *C* instructions, nor does *NASM* have a directive like `.code16gcc`. You'll need to modify the assembly code to push 32-bit values on to the stack in real mode. You will also need to override the `call` instruction so that the return address needs to be treated as a 32-bit value, not 16-bit. This code:
```
push welcome
call print_str ;call function
```
Should be:
```
jmp 0x0000:setcs
setcs:
cld
push dword welcome
call dword print_str ;call function
```
*GCC* has a requirement that the direction flag be cleared before calling any *C* function. I added the *CLD* instruction to the top of the assembly code to make sure this is the case. *GCC* code also needs to have *CS* to 0x0000 to work properly. The *FAR JMP* does just that.
You can also drop the `__asm__(".code16gcc\n");` on modern *GCC* that supports the `-m16` option. `-m16` automatically places a `.code16gcc` into the file that is being compiled.
Since *GCC* also uses the full 32-bit stack pointer it is a good idea to initialize *ESP* with 0x7c00, not just *SP*. Change `mov sp, 0x7C00` to `mov esp, 0x7C00`. This ensures the full 32-bit stack pointer is 0x7c00.
The modified `kmain.c` code should now look like:
```
#include <stdint.h>
void print_str(char *str) {
while (*str) {
/* AH=0x0e, AL=char to print, BH=page, BL=fg color */
__asm__ __volatile__ ("int $0x10"
:
: "a" ((0x0e<<8) | *str++),
"b" (0x0000));
}
}
```
and `hw.asm`:
```
extern print_str
global start
bits 16
section .text
start:
xor ax, ax ; AX = 0
mov ds, ax
mov es, ax
mov ss, ax
mov esp, 0x7C00
jmp 0x0000:setcs ; Set CS to 0
setcs:
cld ; GCC code requires direction flag to be cleared
push dword welcome
call dword print_str ; call function
cli
hlt
section .data
welcome db 'Developped by Marius Van Nieuwenhuyse', 0x0D, 0x0A, 0
```
These commands can be build the bootloader with:
```
gcc -fno-PIC -ffreestanding -m16 -c kmain.c -o kmain.o
ld -melf_i386 --build-id=none -T link.ld kmain.o hw.o -o kernel.elf
objcopy -O binary kernel.elf kernel.bin
```
When run with `qemu-system-i386 -fda kernel.bin` it should look simialr to:
[](https://i.stack.imgur.com/hJYfX.png)
---
In Most Cases GCC Produces Code that Requires 80386+
----------------------------------------------------
There are number of disadvantages to *GCC* generated code using `.code16gcc`:
* ES=DS=CS=SS must be 0
* Code must fit in the first 64kb
* *GCC* code has no understanding of 20-bit segment:offset addressing.
* For anything but the most trivial *C* code, GCC doesn't generate code that can run on a 286/186/8086. It runs in real mode but it uses 32-bit operands and addressing not available on processors earlier than 80386.
* If you want to access memory locations above the first 64kb then you need to be in [**Unreal Mode**(big)](http://wiki.osdev.org/Unreal_Mode#Big_Unreal_Mode) before calling into *C* code.
If you want to produce real 16-bit code from a more modern *C* compiler I recommend [**OpenWatcom C**](http://www.openwatcom.org/)
* The inline assembly is not as powerful as *GCC*
* The inline assembly syntax is different but it is easier to use and less error prone than *GCC*'s inline assembly.
* Can generate code that will run on antiquated 8086/8088 processors.
* Understands 20-bit segment:offset real mode addressing and supports the concept of far and huge pointers.
* `wlink` the Watcom linker can produce basic flat binary files usable as a bootloader.
---
Zero Fill the BSS Section
-------------------------
The BIOS boot sequence doesn't guarantee that memory is actually zero. This causes a potential problem for the zero initialized region *BSS*. Before calling into *C* code for the first time the region should be zero filled by our assembly code. The linker script I originally wrote defines a symbol `__bss_start` that is the offset of the *BSS* memory and `__bss_sizeb` is the size in bytes. Using this info you can use the *STOSB* instruction to easily zero fill it. At the top of `hw.asm` you can add:
```
extern __bss_sizeb
extern __bss_start
```
And after the *CLD* instruction and before calling any *C* code you can do the zero fill this way:
```
; Zero fill the BSS section
mov cx, __bss_sizeb ; Size of BSS computed in linker script
mov di, __bss_start ; Start of BSS defined in linker script
rep stosb ; AL still zero, Fill memory with zero
```
---
Other Suggestions
-----------------
To reduce the bloat of the code generated by the compiler it can be useful to use `-fomit-frame-pointer`. Compiling with `-Os` can optimize for space (rather than speed). We have limited space (512 bytes) for the initial code loaded by the BIOS so these optimizations can be beneficial. The command line for compiling could appear as:
```
gcc -fno-PIC -fomit-frame-pointer -ffreestanding -m16 -Os -c kmain.c -o kmain.o
```
|
>
> I write a boot loader in asm and want to add some compiled C code in my project.
>
>
>
Then you need to use a 16-bit x86 compiler, such as [OpenWatcom](http://www.openwatcom.org/).
**GCC cannot safely build real-mode code**, as it is unaware of some important features of the platform, including memory segmentation. Inserting the `.code16` directive will make the compiler generate incorrect output. Despite appearing in many tutorials, this piece of advice is simply incorrect, and should not be used.
|
47,249,699 |
I write a boot loader in asm and want to add some compiled C code in my project.
I created a test function here:
**test.c**
```
__asm__(".code16\n");
void print_str() {
__asm__ __volatile__("mov $'A' , %al\n");
__asm__ __volatile__("mov $0x0e, %ah\n");
__asm__ __volatile__("int $0x10\n");
}
```
And here is the asm code (the boot loader):
**hw.asm**
```
[org 0x7C00]
[BITS 16]
[extern print_str] ;nasm tip
start:
mov ax, 0
mov ds, ax
mov es, ax
mov ss, ax
mov sp, 0x7C00
mov si, name
call print_string
mov al, ' '
int 10h
mov si, version
call print_string
mov si, line_return
call print_string
call print_str ;call function
mov si, welcome
call print_string
jmp mainloop
mainloop:
mov si, prompt
call print_string
mov di, buffer
call get_str
mov si, buffer
cmp byte [si], 0
je mainloop
mov si, buffer
;call print_string
mov di, cmd_version
call strcmp
jc .version
jmp mainloop
.version:
mov si, name
call print_string
mov al, ' '
int 10h
mov si, version
call print_string
mov si, line_return
call print_string
jmp mainloop
name db 'MOS', 0
version db 'v0.1', 0
welcome db 'Developped by Marius Van Nieuwenhuyse', 0x0D, 0x0A, 0
prompt db '>', 0
line_return db 0x0D, 0x0A, 0
buffer times 64 db 0
cmd_version db 'version', 0
%include "functions/print.asm"
%include "functions/getstr.asm"
%include "functions/strcmp.asm"
times 510 - ($-$$) db 0
dw 0xaa55
```
I need to call the c function like a simple asm function
Without the extern and the call `print_str`, the asm script boot in VMWare.
I tried to compile with:
```
nasm -f elf32
```
***But i can't call org 0x7C00***
|
2017/11/12
|
[
"https://Stackoverflow.com/questions/47249699",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5562200/"
] |
Compiling & Linking NASM and GCC Code
-------------------------------------
This question has a more complex answer than one might believe, although it is possible. Can the first stage of a bootloader (the original 512 bytes that get loaded at physical address 0x07c00) make a call into a *C* function? Yes, but it requires rethinking how you build your project.
For this to work you can no longer us `-f bin` with *NASM*. This also means you can't use the `org 0x7c00` to tell the assembler what address the code expects to start from. You'll need to do this through a linker (either us *LD* directly or *GCC* for linking). Since the linker will lay things out in memory we can't rely on placing the boot sector signature `0xaa55` in our output file. We can get the linker to do that for us.
The first problem you will discover is that the default linker scripts used internally by *GCC* don't lay things out the way we want. We'll need to create our own. Such a linker script will have to set the origin point (Virtual Memory Address aka VMA) to 0x7c00, place the code from your assembly file before the data and place the boot signature at offset 510 in the file. I'm not going to write a tutorial on Linker scripts. The [Binutils Documentation](https://sourceware.org/binutils/docs/ld/Scripts.html#Scripts) contains almost everything you need to know about linker scripts.
```
OUTPUT_FORMAT("elf32-i386");
/* We define an entry point to keep the linker quiet. This entry point
* has no meaning with a bootloader in the binary image we will eventually
* generate. Bootloader will start executing at whatever is at 0x07c00 */
ENTRY(start);
SECTIONS
{
. = 0x7C00;
.text : {
/* Place the code in hw.o before all other code */
hw.o(.text);
*(.text);
}
/* Place the data after the code */
.data : SUBALIGN(2) {
*(.data);
*(.rodata*);
}
/* Place the boot signature at LMA/VMA 0x7DFE */
.sig 0x7DFE : {
SHORT(0xaa55);
}
/* Place the uninitialised data in the area after our bootloader
* The BIOS only reads the 512 bytes before this into memory */
.bss : SUBALIGN(4) {
__bss_start = .;
*(COMMON);
*(.bss)
. = ALIGN(4);
__bss_end = .;
}
__bss_sizeb = SIZEOF(.bss);
/* Remove sections that won't be relevant to us */
/DISCARD/ : {
*(.eh_frame);
*(.comment);
}
}
```
This script should create an *ELF* executable that can be converted to a flat binary file with *OBJCOPY*. We could have output as a binary file directly but I separate the two processes out in the event I want to include debug information in the *ELF* version for debug purposes.
Now that we have a linker script we must remove the `ORG 0x7c00` and the boot signature. For simplicity sake we'll try to get the following code (`hw.asm`) to work:
```
extern print_str
global start
bits 16
section .text
start:
xor ax, ax ; AX = 0
mov ds, ax
mov es, ax
mov ss, ax
mov sp, 0x7C00
call print_str ; call function
/* Halt the processor so we don't keep executing code beyond this point */
cli
hlt
```
You can include all your other code, but this sample will still demonstrate the basics of calling into a *C* function.
Assume the code above you can now generate the *ELF* object from `hw.asm` producing `hw.o` using this command:
```
nasm -f elf32 hw.asm -o hw.o
```
You compile each *C* file with something like:
```
gcc -ffreestanding -c kmain.c -o kmain.o
```
I placed the *C* code you had into a file called `kmain.c` . The command above will generate `kmain.o`. I noticed you aren't using a cross compiler so you'll want to use `-fno-PIE` to ensure we don't generate relocatable code. `-ffreestanding` tells GCC the *C* standard library may not exist, and `main` may not be the program entry point. You'd compile each *C* file in the same way.
To link this code to a final executable and then produce a flat binary file that can be booted we do this:
```
ld -melf_i386 --build-id=none -T link.ld kmain.o hw.o -o kernel.elf
objcopy -O binary kernel.elf kernel.bin
```
You specify all the object files to link with the *LD* command. The *LD* command above will produce a 32-bit ELF executable called `kernel.elf`. This file can be useful in the future for debugging purposes. Here we use *OBJCOPY* to convert `kernel.elf` to a binary file called `kernel.bin`. `kernel.bin` can be used as a bootloader image.
You should be able to run it with *QEMU* using this command:
```
qemu-system-i386 -fda kernel.bin
```
When run it may look like:
[](https://i.stack.imgur.com/IIXKl.png)
You'll notice the letter `A` appears on the last line. This is what we'd expect from the `print_str` code.
---
GCC Inline Assembly is Hard to Get Right
----------------------------------------
If we take your example code in the question:
```
__asm__ __volatile__("mov $'A' , %al\n");
__asm__ __volatile__("mov $0x0e, %ah\n");
__asm__ __volatile__("int $0x10\n");
```
The compiler is free to reorder these `__asm__` statements if it wanted to. The `int $0x10` could appear before the MOV instructions. If you want these 3 lines to be output in this exact order you can combine them into one like this:
```
__asm__ __volatile__("mov $'A' , %al\n\t"
"mov $0x0e, %ah\n\t"
"int $0x10");
```
These are basic assembly statements. It's not required to specify `__volatile__`on them as they are already [implicitly volatile](https://gcc.gnu.org/onlinedocs/gcc/Basic-Asm.html#Basic-Asm), so it has no effect. From the original poster's answer it is clear they want to eventually use variables in `__asm__` blocks. This is doable with [extended inline assembly](https://gcc.gnu.org/onlinedocs/gcc/Extended-Asm.html#Extended-Asm) (the instruction string is followed by a colon `:` followed by constraints.):
With extended asm you can read and write C variables from assembler and perform jumps from assembler code to C labels. Extended asm syntax uses colons (‘:’) to delimit the operand parameters after the assembler template:
>
>
> ```
> asm [volatile] ( AssemblerTemplate
> : OutputOperands
> [ : InputOperands
> [ : Clobbers ] ])
>
> ```
>
>
This answer isn't a tutorial on inline assembly. The general rule of thumb is that one [should not use inline assembly unless you have to](https://gcc.gnu.org/wiki/DontUseInlineAsm). Inline assembly done wrong can create hard to track bugs or have unusual side effects. Unfortunately doing 16-bit interrupts in *C* pretty much requires it, or you write the entire function in assembly (ie: NASM).
This is an example of a `print_chr` function that take a nul terminated string and prints each character out one by one using [Int 10h/ah=0ah](http://www.ctyme.com/intr/rb-0106.htm):
```
#include <stdint.h>
__asm__(".code16gcc\n");
void print_str(char *str) {
while (*str) {
/* AH=0x0e, AL=char to print, BH=page, BL=fg color */
__asm__ __volatile__ ("int $0x10"
:
: "a" ((0x0e<<8) | *str++),
"b" (0x0000));
}
}
```
`hw.asm` would be modified to look like this:
```
push welcome
call print_str ;call function
```
The idea when this is assembled/compiled (using the commands in the first section of this answer) and run is that it print out the `welcome` message. Unfortunately it will almost never work, and may even crash some emulators like *QEMU*.
---
code16 is Almost Useless and Should Not be Used
-----------------------------------------------
In the last section we learn that a simple function that takes a parameter ends up not working and may even crash an emulator like *QEMU*. The main problem is that the `__asm__(".code16\n");` statement really doesn't work well with the code generated by *GCC*. The [Binutils AS documentation](https://sourceware.org/binutils/docs/as/i386_002d16bit.html) says:
>
> ‘.code16gcc’ provides experimental support for generating 16-bit code from gcc, and differs from ‘.code16’ in that ‘call’, ‘ret’, ‘enter’, ‘leave’, ‘push’, ‘pop’, ‘pusha’, ‘popa’, ‘pushf’, and ‘popf’ instructions default to 32-bit size. This is so that the stack pointer is manipulated in the same way over function calls, allowing access to function parameters at the same stack offsets as in 32-bit mode. ‘.code16gcc’ also automatically adds address size prefixes where necessary to use the 32-bit addressing modes that gcc generates.
>
>
>
`.code16gcc` is what you really need to be using, not `.code16`. This force GNU assembler on the back end to emit address and operand prefixes on certain instructions so that the addresses and operands are treated as 4 bytes wide, and not 2 bytes.
The hand written code in *NASM* doesn't know it will be calling *C* instructions, nor does *NASM* have a directive like `.code16gcc`. You'll need to modify the assembly code to push 32-bit values on to the stack in real mode. You will also need to override the `call` instruction so that the return address needs to be treated as a 32-bit value, not 16-bit. This code:
```
push welcome
call print_str ;call function
```
Should be:
```
jmp 0x0000:setcs
setcs:
cld
push dword welcome
call dword print_str ;call function
```
*GCC* has a requirement that the direction flag be cleared before calling any *C* function. I added the *CLD* instruction to the top of the assembly code to make sure this is the case. *GCC* code also needs to have *CS* to 0x0000 to work properly. The *FAR JMP* does just that.
You can also drop the `__asm__(".code16gcc\n");` on modern *GCC* that supports the `-m16` option. `-m16` automatically places a `.code16gcc` into the file that is being compiled.
Since *GCC* also uses the full 32-bit stack pointer it is a good idea to initialize *ESP* with 0x7c00, not just *SP*. Change `mov sp, 0x7C00` to `mov esp, 0x7C00`. This ensures the full 32-bit stack pointer is 0x7c00.
The modified `kmain.c` code should now look like:
```
#include <stdint.h>
void print_str(char *str) {
while (*str) {
/* AH=0x0e, AL=char to print, BH=page, BL=fg color */
__asm__ __volatile__ ("int $0x10"
:
: "a" ((0x0e<<8) | *str++),
"b" (0x0000));
}
}
```
and `hw.asm`:
```
extern print_str
global start
bits 16
section .text
start:
xor ax, ax ; AX = 0
mov ds, ax
mov es, ax
mov ss, ax
mov esp, 0x7C00
jmp 0x0000:setcs ; Set CS to 0
setcs:
cld ; GCC code requires direction flag to be cleared
push dword welcome
call dword print_str ; call function
cli
hlt
section .data
welcome db 'Developped by Marius Van Nieuwenhuyse', 0x0D, 0x0A, 0
```
These commands can be build the bootloader with:
```
gcc -fno-PIC -ffreestanding -m16 -c kmain.c -o kmain.o
ld -melf_i386 --build-id=none -T link.ld kmain.o hw.o -o kernel.elf
objcopy -O binary kernel.elf kernel.bin
```
When run with `qemu-system-i386 -fda kernel.bin` it should look simialr to:
[](https://i.stack.imgur.com/hJYfX.png)
---
In Most Cases GCC Produces Code that Requires 80386+
----------------------------------------------------
There are number of disadvantages to *GCC* generated code using `.code16gcc`:
* ES=DS=CS=SS must be 0
* Code must fit in the first 64kb
* *GCC* code has no understanding of 20-bit segment:offset addressing.
* For anything but the most trivial *C* code, GCC doesn't generate code that can run on a 286/186/8086. It runs in real mode but it uses 32-bit operands and addressing not available on processors earlier than 80386.
* If you want to access memory locations above the first 64kb then you need to be in [**Unreal Mode**(big)](http://wiki.osdev.org/Unreal_Mode#Big_Unreal_Mode) before calling into *C* code.
If you want to produce real 16-bit code from a more modern *C* compiler I recommend [**OpenWatcom C**](http://www.openwatcom.org/)
* The inline assembly is not as powerful as *GCC*
* The inline assembly syntax is different but it is easier to use and less error prone than *GCC*'s inline assembly.
* Can generate code that will run on antiquated 8086/8088 processors.
* Understands 20-bit segment:offset real mode addressing and supports the concept of far and huge pointers.
* `wlink` the Watcom linker can produce basic flat binary files usable as a bootloader.
---
Zero Fill the BSS Section
-------------------------
The BIOS boot sequence doesn't guarantee that memory is actually zero. This causes a potential problem for the zero initialized region *BSS*. Before calling into *C* code for the first time the region should be zero filled by our assembly code. The linker script I originally wrote defines a symbol `__bss_start` that is the offset of the *BSS* memory and `__bss_sizeb` is the size in bytes. Using this info you can use the *STOSB* instruction to easily zero fill it. At the top of `hw.asm` you can add:
```
extern __bss_sizeb
extern __bss_start
```
And after the *CLD* instruction and before calling any *C* code you can do the zero fill this way:
```
; Zero fill the BSS section
mov cx, __bss_sizeb ; Size of BSS computed in linker script
mov di, __bss_start ; Start of BSS defined in linker script
rep stosb ; AL still zero, Fill memory with zero
```
---
Other Suggestions
-----------------
To reduce the bloat of the code generated by the compiler it can be useful to use `-fomit-frame-pointer`. Compiling with `-Os` can optimize for space (rather than speed). We have limited space (512 bytes) for the initial code loaded by the BIOS so these optimizations can be beneficial. The command line for compiling could appear as:
```
gcc -fno-PIC -fomit-frame-pointer -ffreestanding -m16 -Os -c kmain.c -o kmain.o
```
|
First i want to express how to link C compiled code with assembled file.
I put together some Q/A in SO and reach to this.
***C code:***
**func.c**
```
//__asm__(".code16gcc\n");when we use eax, 32 bit reg we cant use this as truncate
//problem
#include <stdio.h>
int x = 0;
int madd(int a, int b)
{
return a + b;
}
void mexit(){
__asm__ __volatile__("mov $0, %ebx\n");
__asm__ __volatile__("mov $1, %eax \n");
__asm__ __volatile__("int $0x80\n");
}
char* tmp;
///how to direct use of arguments in asm command
void print_str(int a, char* s){
x = a;
__asm__("mov x, %edx\n");// ;third argument: message length
tmp = s;
__asm__("mov tmp, %ecx\n");// ;second argument: pointer to message to write
__asm__("mov $1, %ebx\n");//first argument: file handle (stdout)
__asm__("mov $4, %eax\n");//system call number (sys_write)
__asm__ __volatile__("int $0x80\n");//call kernel
}
void mtest(){
printf("%s\n", "Hi");
//putchar('a');//why not work
}
///gcc -c func.c -o func
```
***Assembly code:***
**hello.asm**
```
extern mtest
extern printf
extern putchar
extern print_str
extern mexit
extern madd
section .text ;section declaration
;we must export the entry point to the ELF linker or
global _start ;loader. They conventionally recognize _start as their
;entry point. Use ld -e foo to override the default.
_start:
;write our string to stdout
push msg
push len
call print_str;
call mtest ;print "Hi"; call printf inside a void function
; use add inside func.c
push 5
push 10
call madd;
;direct call of <stdio.h> printf()
push eax
push format
call printf; ;printf(format, eax)
call mexit; ;exit to OS
section .data ;section declaration
format db "%d", 10, 0
msg db "Hello, world!",0xa ;our dear string
len equ $ - msg ;length of our dear string
; nasm -f elf32 hello.asm -o hello
;Link two files
;ld hello func -o hl -lc -I /lib/ld-linux.so.2
; ./hl run code
;chain to assemble, compile, Run
;; gcc -c func.c -o func && nasm -f elf32 hello.asm -o hello && ld hello func -o hl -lc -I /lib/ld-linux.so.2 && echo &&./hl
```
***Chain commands for assemble, compile and Run***
>
> `gcc -c func.c -o func && nasm -f elf32 hello.asm -o hello && ld hello func -o hl -lc -I /lib/ld-linux.so.2 && echo && ./hl`
>
>
>
***Edit[toDO]***
* Write boot loader code instead of this version
* Some explanation on how ld, gcc, nasm works.
|
57,375,509 |
I have events table, now I want to display the most frequent element in a column using SQL
Here is the event table.
```
id | selectedcountries
0 | Tanzania
1 | Tanzania
2 | Tanzania
3 | Kenya
4 | Uganda
5 | Uganda
6 | Kenya
7 | Uganda
8 | Tanzania
8 | Poland
9 | Poland
10 | Tanzania
```
>
> UPDATE
>
>
> For example, for this table it should return Tanzania since it is the
> most frequent value:
>
>
>
Here is my solution
```
SELECT selectedcountries, COUNT( 'selectedcountries' ) AS 'country'
FROM EVENTS
GROUP BY 'selectedcountries'
ORDER BY 'country' DESC
```
Unfortunately, I am getting the following
```
selectedcountries country
73
```
[](https://i.stack.imgur.com/80puD.png)
What do I need to do to get what I want?
|
2019/08/06
|
[
"https://Stackoverflow.com/questions/57375509",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9964622/"
] |
Finally I have discovered a way to do that with CSS only, which is as follows:
HTML
```
<body>
<form>
<input type="text" />
<input type="submit" />
</form>
<table>
<thead></thead>
<tbody>
<tr>
<td>table data 1</td>
<td>table data 2</td>
</tr>
<tr>
<td>table data 1</td>
<td>table data 2</td>
</tr>
</tbody>
</table>
</body>
```
CSS
```
body {
position: relative;
}
input {
display: block;
}
input[type="submit"] {
position: absolute;
bottom: 0;
}
table {
padding-bottom: 20px;
}
```
|
Please check code.
html
```
<form>
<input type="text" />
<table>
<thead></thead>
<tbody>
<tr>
<td>table data 1</td>
<td>table data 2</td>
</tr>
</tbody>
</table>
<input type="submit" />
</form>
```
css
```
input[type="submit"] {
margin-top: 50px;
}
```
or you can visit given url also - <https://codepen.io/piyushjn/pen/eqyXaM>
Let me know if you need anything.
|
4,396,900 |
Just as I described in the question, if $ f(x)$ is continuous on $[0,\infty]$ and
$$ \displaystyle \lim\_{x\to \infty} f(x)=1$$
Then what about this integration?
$$\displaystyle \int\_0^\infty f(x) dx$$
For me, I'm a little bit suspicious that the integration is guaranteed to be divergent. My idea is from function $\dfrac{\sin x}{x}$ that is a continuous function. At the same time: $$ \lim\_{x\to \infty}\dfrac{\sin x}{x}=0$$ and $$ \int\_0 ^\infty \dfrac{\sin x}{x} \ dx =\dfrac{\pi}{2}$$
This function is "oscillating" up and down on the x-axis in a suitable way resulting in it being convergent.
Then, I think that maybe there can also exist a function, but it is oscillating on $ y=1$ in a very suitable way which makes it convergent
---
Failed example, plz ignore this:
Then I think by constructing a piece wise continuous function:
$$\begin{cases}
f(x) = \dfrac{\sin x}{x} +1 & \forall x\in[2k\pi,(2k+1)\pi] \\ \\
f(x) = \dfrac{\sin x}{x} -1 & \forall x\in[(2k+1)\pi,(2k+2)\pi]
\end{cases}$$ for $k=0,1,2...$
---
But I'm not certain whether my idea is right and can't really come up with any counterexamples.
Also if the integration is indeed guaranteed to be divergent, I don't know how to prove it.
Any helps? Thanks!
|
2022/03/06
|
[
"https://math.stackexchange.com/questions/4396900",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/993159/"
] |
Continuity is not required. Since $\lim\_{x\to\infty} f(x)=1$, there is some $x\_0>0$ such that for all $x>x\_0$ we have $f(x)>\frac{1}{2}$. In order for $\int\_0^{\infty} f(x) \, dx$ to converge $\int\_{x\_0}^{\infty} f(x) \, dx$ must converge.
$\int\_{x\_0}^{\infty} \frac{1}{2} \, dx$ clearly diverges, as $\int\_{x\_0}^{x} \frac{1}{2} \, dx = \frac{1}{2}(x-x\_0)\overset{x\to\infty}{\to}\infty$. By the comparison test $\int\_{x\_0}^{\infty} f(x)\,dx$ diverges as well, so that $\int\_0^{\infty} f(x) \, dx$ necessarily diverges.
|
Yes, even if $\int\_{0}^{\infty}f(x)dx$ is defined in improper sense.
Let $F(x)=\int\_{0}^{x}f(t)dt$. Suppose the contrary that $I=\lim\_{x\rightarrow\infty}F(x)$
exists. For $\varepsilon=1$, there exists $x\_{1}>0$ such that $|F(x)-I|<\varepsilon$
whenever $x\geq x\_{1}$. Since $\lim\_{x\rightarrow\infty}f(x)=1>\frac{1}{2}$,
there exists $x\_{2}>0$ such that $f(x)>\frac{1}{2}$ whenever $x\geq x\_{2}$.
Take $x\_{3}=\max(x\_{1},x\_{2})+1$, $x\_{4}=x\_{3}+100$. On one hand,
\begin{eqnarray\*}
|F(x\_{4})-F(x\_{3})| & \leq & \left|F(x\_{3})-I\right|+\left|F(x\_{4})-I\right|\\
& < & 2\varepsilon\\
& = & 2.
\end{eqnarray\*}
On the other hand,
\begin{eqnarray\*}
& & |F(x\_{4})-F(x\_{3})|\\
& = & \left|\int\_{x\_{3}}^{x\_{4}}f(t)dt\right|\\
& \geq & \int\_{x\_{3}}^{x\_{4}}\frac{1}{2}dt\\
& = & \frac{1}{2}(x\_{4}-x\_{3})\\
& = & 50.
\end{eqnarray\*}
We obtain a contradiction.
|
4,396,900 |
Just as I described in the question, if $ f(x)$ is continuous on $[0,\infty]$ and
$$ \displaystyle \lim\_{x\to \infty} f(x)=1$$
Then what about this integration?
$$\displaystyle \int\_0^\infty f(x) dx$$
For me, I'm a little bit suspicious that the integration is guaranteed to be divergent. My idea is from function $\dfrac{\sin x}{x}$ that is a continuous function. At the same time: $$ \lim\_{x\to \infty}\dfrac{\sin x}{x}=0$$ and $$ \int\_0 ^\infty \dfrac{\sin x}{x} \ dx =\dfrac{\pi}{2}$$
This function is "oscillating" up and down on the x-axis in a suitable way resulting in it being convergent.
Then, I think that maybe there can also exist a function, but it is oscillating on $ y=1$ in a very suitable way which makes it convergent
---
Failed example, plz ignore this:
Then I think by constructing a piece wise continuous function:
$$\begin{cases}
f(x) = \dfrac{\sin x}{x} +1 & \forall x\in[2k\pi,(2k+1)\pi] \\ \\
f(x) = \dfrac{\sin x}{x} -1 & \forall x\in[(2k+1)\pi,(2k+2)\pi]
\end{cases}$$ for $k=0,1,2...$
---
But I'm not certain whether my idea is right and can't really come up with any counterexamples.
Also if the integration is indeed guaranteed to be divergent, I don't know how to prove it.
Any helps? Thanks!
|
2022/03/06
|
[
"https://math.stackexchange.com/questions/4396900",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/993159/"
] |
Yes, even if $\int\_{0}^{\infty}f(x)dx$ is defined in improper sense.
Let $F(x)=\int\_{0}^{x}f(t)dt$. Suppose the contrary that $I=\lim\_{x\rightarrow\infty}F(x)$
exists. For $\varepsilon=1$, there exists $x\_{1}>0$ such that $|F(x)-I|<\varepsilon$
whenever $x\geq x\_{1}$. Since $\lim\_{x\rightarrow\infty}f(x)=1>\frac{1}{2}$,
there exists $x\_{2}>0$ such that $f(x)>\frac{1}{2}$ whenever $x\geq x\_{2}$.
Take $x\_{3}=\max(x\_{1},x\_{2})+1$, $x\_{4}=x\_{3}+100$. On one hand,
\begin{eqnarray\*}
|F(x\_{4})-F(x\_{3})| & \leq & \left|F(x\_{3})-I\right|+\left|F(x\_{4})-I\right|\\
& < & 2\varepsilon\\
& = & 2.
\end{eqnarray\*}
On the other hand,
\begin{eqnarray\*}
& & |F(x\_{4})-F(x\_{3})|\\
& = & \left|\int\_{x\_{3}}^{x\_{4}}f(t)dt\right|\\
& \geq & \int\_{x\_{3}}^{x\_{4}}\frac{1}{2}dt\\
& = & \frac{1}{2}(x\_{4}-x\_{3})\\
& = & 50.
\end{eqnarray\*}
We obtain a contradiction.
|
Divergence is definitely guaranteed. Consider this: suppose that $f$ has an antiderivative $F.$ Then by L'Hopital's theorem, $$\lim\_{x\to\infty}\frac{F(x)}{x}=\lim\_{x\to\infty}f(x).$$ By the fundamental theorem of calculus, since $f$ is continuous, you are guaranteed that $$F(x)=\int\_a^xf(t)\,\mathrm{d}t$$ for some $a.$ Therefore, $$\lim\_{x\to\infty}\frac{\int\_a^xf(t)\,\mathrm{d}t}{x}=1.$$ However, $$\lim\_{x\to\infty}x=\infty,$$ so it necessarily is the case that $$\lim\_{x\to\infty}\int\_a^xf(t)\,\mathrm{d}t=\int\_a^{\infty}f(t)\,\mathrm{d}t=\infty$$ as well. Why? Because if the integral were finite, then $$\lim\_{x\to\infty}\frac{\int\_a^xf(t)\,\mathrm{d}t}{x}=0.$$
|
4,396,900 |
Just as I described in the question, if $ f(x)$ is continuous on $[0,\infty]$ and
$$ \displaystyle \lim\_{x\to \infty} f(x)=1$$
Then what about this integration?
$$\displaystyle \int\_0^\infty f(x) dx$$
For me, I'm a little bit suspicious that the integration is guaranteed to be divergent. My idea is from function $\dfrac{\sin x}{x}$ that is a continuous function. At the same time: $$ \lim\_{x\to \infty}\dfrac{\sin x}{x}=0$$ and $$ \int\_0 ^\infty \dfrac{\sin x}{x} \ dx =\dfrac{\pi}{2}$$
This function is "oscillating" up and down on the x-axis in a suitable way resulting in it being convergent.
Then, I think that maybe there can also exist a function, but it is oscillating on $ y=1$ in a very suitable way which makes it convergent
---
Failed example, plz ignore this:
Then I think by constructing a piece wise continuous function:
$$\begin{cases}
f(x) = \dfrac{\sin x}{x} +1 & \forall x\in[2k\pi,(2k+1)\pi] \\ \\
f(x) = \dfrac{\sin x}{x} -1 & \forall x\in[(2k+1)\pi,(2k+2)\pi]
\end{cases}$$ for $k=0,1,2...$
---
But I'm not certain whether my idea is right and can't really come up with any counterexamples.
Also if the integration is indeed guaranteed to be divergent, I don't know how to prove it.
Any helps? Thanks!
|
2022/03/06
|
[
"https://math.stackexchange.com/questions/4396900",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/993159/"
] |
Continuity is not required. Since $\lim\_{x\to\infty} f(x)=1$, there is some $x\_0>0$ such that for all $x>x\_0$ we have $f(x)>\frac{1}{2}$. In order for $\int\_0^{\infty} f(x) \, dx$ to converge $\int\_{x\_0}^{\infty} f(x) \, dx$ must converge.
$\int\_{x\_0}^{\infty} \frac{1}{2} \, dx$ clearly diverges, as $\int\_{x\_0}^{x} \frac{1}{2} \, dx = \frac{1}{2}(x-x\_0)\overset{x\to\infty}{\to}\infty$. By the comparison test $\int\_{x\_0}^{\infty} f(x)\,dx$ diverges as well, so that $\int\_0^{\infty} f(x) \, dx$ necessarily diverges.
|
Divergence is definitely guaranteed. Consider this: suppose that $f$ has an antiderivative $F.$ Then by L'Hopital's theorem, $$\lim\_{x\to\infty}\frac{F(x)}{x}=\lim\_{x\to\infty}f(x).$$ By the fundamental theorem of calculus, since $f$ is continuous, you are guaranteed that $$F(x)=\int\_a^xf(t)\,\mathrm{d}t$$ for some $a.$ Therefore, $$\lim\_{x\to\infty}\frac{\int\_a^xf(t)\,\mathrm{d}t}{x}=1.$$ However, $$\lim\_{x\to\infty}x=\infty,$$ so it necessarily is the case that $$\lim\_{x\to\infty}\int\_a^xf(t)\,\mathrm{d}t=\int\_a^{\infty}f(t)\,\mathrm{d}t=\infty$$ as well. Why? Because if the integral were finite, then $$\lim\_{x\to\infty}\frac{\int\_a^xf(t)\,\mathrm{d}t}{x}=0.$$
|
26,674,984 |
I have an array of objects example
```
var objects = [
{ first_nom: 'dave', value: '5'},
{ first_nom: 'roger', value: '-0'},
{ first_nom: 'pete', value: '+0' },
{ first_nom: 'pete', value: '-5' },
];
```
Sorting this by value would ideally reverse the two zeros.
I have tried the normal javascript/jquery and underscore sorts but they ignore the leading `-` or `+` and probably rightly so.
This is what I currently have (this sorts fine but ignores the + and -):
```
var chartData = _.sortBy(objects, 'value').reverse();
```
Is there anything else someone can recommend please?
Many thanks
Nev
|
2014/10/31
|
[
"https://Stackoverflow.com/questions/26674984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1685866/"
] |
You can special-case them, sorting as strings when both values are `0`:
```js
var objects = [
{ first_nom: 'dave', value: '5'},
{ first_nom: 'roger', value: '-0'},
{ first_nom: 'pete', value: '+0' },
{ first_nom: 'pete', value: '-5' },
];
var sorted = objects.sort(
function(a,b) {
if ((a.value == 0) && (b.value == 0))
{
return b.value.localeCompare(a.value);
}
else
return b.value - a.value;
}
);
console.log(JSON.stringify(sorted));
```
Results in:
```
[
{"first_nom":"dave","value":"5"},
{"first_nom":"pete","value":"+0"},
{"first_nom":"roger","value":"-0"},
{"first_nom":"pete","value":"-5"}
]
```
|
A simple solution is to convert a signed zero to some signed small value, for example:
```js
var objects = [
{ first_nom: 'dave', value: '5'},
{ first_nom: 'pete', value: '+0' },
{ first_nom: 'pete', value: '-5' },
{ first_nom: 'roger', value: '-0'},
];
convert = function(n) {
if(n == '-0') return -Number.EPSILON;
if(n == '+0') return +Number.EPSILON;
return parseInt(n);
}
objects.sort(function(a, b) {
return convert(a.value) - convert(b.value);
});
document.write(JSON.stringify(objects));
```
To do that in a pure numeric way, utilize the fact that
```
Math.atan2(0, -0) === Math.PI
Math.atan2(0, 0) === 0
```
(see [Differentiating +0 and -0](https://stackoverflow.com/q/7223717/989121))
```js
var objects = [
{ first_nom: 'dave', value: '5'},
{ first_nom: 'roger', value: '-0'},
{ first_nom: 'pete', value: '+0' },
{ first_nom: 'pete', value: '-5' },
];
objects.sort(function(a, b) {
a = parseInt(a.value);
b = parseInt(b.value);
return (a || b) ? (b - a) : (Math.atan2(0, a) - Math.atan2(0, b));
});
document.write(JSON.stringify(objects));
```
|
26,674,984 |
I have an array of objects example
```
var objects = [
{ first_nom: 'dave', value: '5'},
{ first_nom: 'roger', value: '-0'},
{ first_nom: 'pete', value: '+0' },
{ first_nom: 'pete', value: '-5' },
];
```
Sorting this by value would ideally reverse the two zeros.
I have tried the normal javascript/jquery and underscore sorts but they ignore the leading `-` or `+` and probably rightly so.
This is what I currently have (this sorts fine but ignores the + and -):
```
var chartData = _.sortBy(objects, 'value').reverse();
```
Is there anything else someone can recommend please?
Many thanks
Nev
|
2014/10/31
|
[
"https://Stackoverflow.com/questions/26674984",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1685866/"
] |
Try the following:
```js
var objects = [
{ first_nom: "dave", value: "5" },
{ first_nom: "roger", value: "-0" },
{ first_nom: "pete", value: "+0" },
{ first_nom: "pete", value: "-5" },
];
objects.sort(function (a, b) {
var x = parseInt(a.value, 10);
var y = parseInt(b.value, 10);
if (x === 0 && y === 0)
return 1 / x - 1 / y || 0;
else return x - y;
});
alert(JSON.stringify(objects, null, 4));
```
The reason this works is because `1 / 0` is `Infinity` whereas `1 / -0` is `-Infinity`.
For example:
1. First case: `x = 0`, `y = 0`:
```
1 / x = Infinity
1 / y = Infinity
Infinity - Infinity = NaN
NaN || 0 = 0
```
Hence the two numbers are left unsorted with respect to each other.
2. Second case: `x = -0`, `y = -0`:
```
1 / x = -Infinity
1 / y = -Infinity
(-Infinity) - (-Infinity) = NaN
NaN || 0 = 0
```
Hence the two numbers are left unsorted with respect to each other.
3. Third case: `x = 0`, `y = -0`:
```
1 / x = Infinity
1 / y = -Infinity
Infinity - (-Infinity) = Infinity
Infinity || 0 = Infinity
```
Hence `x` will come after `y`.
4. Third case: `x = -0`, `y = 0`:
```
1 / x = -Infinity
1 / y = Infinity
(-Infinity) - Infinity = -Infinity
-Infinity || 0 = -Infinity
```
Hence `x` will come before `y`.
That's all that there is to it really.
---
**Edit:** To sort it in reverse order just swap `x` and `y` as follows:
```js
var objects = [
{ first_nom: "dave", value: "5" },
{ first_nom: "roger", value: "-0" },
{ first_nom: "pete", value: "+0" },
{ first_nom: "pete", value: "-5" },
];
objects.sort(function (a, b) {
var x = parseInt(a.value, 10);
var y = parseInt(b.value, 10);
if (x === 0 && y === 0)
return 1 / y - 1 / x || 0;
else return y - x;
});
alert(JSON.stringify(objects, null, 4));
```
Hope that helps.
|
A simple solution is to convert a signed zero to some signed small value, for example:
```js
var objects = [
{ first_nom: 'dave', value: '5'},
{ first_nom: 'pete', value: '+0' },
{ first_nom: 'pete', value: '-5' },
{ first_nom: 'roger', value: '-0'},
];
convert = function(n) {
if(n == '-0') return -Number.EPSILON;
if(n == '+0') return +Number.EPSILON;
return parseInt(n);
}
objects.sort(function(a, b) {
return convert(a.value) - convert(b.value);
});
document.write(JSON.stringify(objects));
```
To do that in a pure numeric way, utilize the fact that
```
Math.atan2(0, -0) === Math.PI
Math.atan2(0, 0) === 0
```
(see [Differentiating +0 and -0](https://stackoverflow.com/q/7223717/989121))
```js
var objects = [
{ first_nom: 'dave', value: '5'},
{ first_nom: 'roger', value: '-0'},
{ first_nom: 'pete', value: '+0' },
{ first_nom: 'pete', value: '-5' },
];
objects.sort(function(a, b) {
a = parseInt(a.value);
b = parseInt(b.value);
return (a || b) ? (b - a) : (Math.atan2(0, a) - Math.atan2(0, b));
});
document.write(JSON.stringify(objects));
```
|
13,283,916 |
I Have created a table model extending DefaultTableModel.
```
public class TableModel extends DefaultTableModel {
List<VariableDetails> data;
public AttachedVariableTableModel(){
super();
this.data=Collections.synchronizedList(new ArrayList<VariableDetails>());
}
//method for adding rows
public void addRow(VariableDetails varDetails){
this.data.add(varDetails);
fireTableRowsInserted(this.data.size()-1,this.data.size()-1);
}
}
```
I tried to add rows to the table which has already data in it.
```
tModel.addRow(new VariableDetails());
```
but rows cannot be added. There is no exceptions and errors. what is actually wrong here? How Can i Solve this? Thanks in advance.
|
2012/11/08
|
[
"https://Stackoverflow.com/questions/13283916",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1548689/"
] |
1. for why reason is there `super();`
2. `DefaultTableModel` can add `Object[]` or `Vector`
3. have to override `AbstractTableModel`, rather than `DefaultTableModel`, have to override all [`get/set` methods](https://stackoverflow.com/a/6901508/714968), with proper `fireXxxXxx()` in the methods, otherwise there aren't something visible in view (`JTable`)
4. can start with [List Table Model](http://tips4java.wordpress.com/2008/11/24/list-table-model/) or [Row Table Model](http://tips4java.wordpress.com/2008/11/21/row-table-model/)
|
May i suggest you a complete table model example to undestand how it works. It also uses a List as data. The most important thing is you need to extends **AbstractTableModel** to use your own variable in order to store data. Here is a complete sample of source code.
```
import java.util.ArrayList;
import java.util.List;
import javax.swing.table.AbstractTableModel;
public class MouseClickTableModel extends AbstractTableModel {
/**
*
*/
private static final long serialVersionUID = -1807522184370383957L;
private final String[] columnNames = { "Sr", "X", "Y", "Delay (ms)",
"Comment" };
public final Class[] mColTypes = { Integer.class, Integer.class,
Integer.class, Integer.class, String.class };
private final List<MouseClick> data;
public MouseClickTableModel(){
data = new ArrayList<MouseClick>(10);
}
public int getColumnCount() {
return columnNames.length;
}
public int getRowCount() {
return data.size();
}
public String getColumnName(int col) {
return columnNames[col];
}
public Object getValueAt(int row, int col) {
final MouseClick currentRow = (MouseClick) data.get(row);
switch (col) {
case 0:
return currentRow.getSequNb();
case 1:
return currentRow.getXcoo();
case 2:
return currentRow.getXycoo();
case 3:
return currentRow.getDelay();
case 4:
return currentRow.getComment();
}
return new String();
}
public Class getColumnClass(int c) {
return mColTypes[c];
}
/*
* Don't need to implement this method unless your table's editable.
*/
public boolean isCellEditable(int row, int col) {
return false;
}
public void updateRow(Object value, int row, int col) {
}
/*
* Don't need to implement this method unless your table's data can change.
*/
@Override
public void setValueAt(Object value, int row, int col) {
MouseClick currentRow = null;
if (row >= data.size()) {
// new data
currentRow = new MouseClick();
data.add(0, currentRow);
}
// update row
else {
currentRow = (MouseClick) data.get(row);
}
switch (col) {
case 0:
currentRow.setSequNb(((Integer) value).intValue());
break;
case 1:
currentRow.setXcoo(((Integer) value).intValue());
break;
case 2:
currentRow.setXycoo(((Integer) value).intValue());
break;
case 3:
currentRow.setDelay(((Integer) value).intValue());
break;
case 4:
currentRow.setComment(((String) value).toString());
break;
}
// update
fireTableCellUpdated(row, col);
}
public MouseClick getData(int row) {
return data.get(row);
}
public void addMouseClick(MouseClick mc) {
insertMouseClick(getRowCount(), mc);
}
public void insertMouseClick(int row, MouseClick mc) {
data.add(row, mc);
fireTableRowsInserted(row, row);
}
public void removeMouseClick(int row) {
data.remove(row);
fireTableRowsDeleted(row, row);
}
}
```
Then you just have to update your model with your ui design.
```
JTable table = new JTable(new MouseClickTableModel());
table.setPreferredScrollableViewportSize(new Dimension(500, 70));
table.setFillsViewportHeight(true);
MouseClickTableModel model = getTable().getModel());
model.insertMouseClick(0, new MouseClick(0, Integer.valueOf(xValue), Integer.valueOf(yValue), 2000, "comment"));
```
|
200,210 |
I want to run a new 20A service and 2x POE lines from my basement to my garage. Can I put them in the same pieces of conduit or do I need two? Piece of conduit would be less than 1 foot in length.
|
2020/08/03
|
[
"https://diy.stackexchange.com/questions/200210",
"https://diy.stackexchange.com",
"https://diy.stackexchange.com/users/121696/"
] |
No, you cannot mix AC mains and low-voltage wiring (such as network cables) in the same conduit. The length of the run is not important, it's prohibited.
Run two separate conduits and you'll be good.
|
There's a gizmo made for *precisely this sort of job*
-----------------------------------------------------
While Exception 1 to NEC 800.133(A)(1)(c) or 800.133(A)(2) would permit the shared sleeve you describe, I would not bother with your conduit sleeve approach here to begin with as the fireblocking foam fill would create issues with potential cable damage during re-entry that could be quite troublesome. Instead, if you don't mind spending a bit of money on the problem to save you a lot of fuss with foam later, I would throw a made-for-purpose gadget at this job, the [STI EZ-Path 22](https://www.stifirestop.com/products/ez-path-series-22/). These are available through various industrial and electrical suppliers for under $100 at the time of this writing, and provide an easy-to-install, easy-to-reenter, and *proven safe* (the device I describe is UL and FM approved for full-blown penetration firestopping in places like hospitals and high-rises where that stuff matters) solution to the problem.
|
1,553,377 |
i want to create a page with frame set
first i divide the page in 3 rows. In second row i divide it by 2 coloumns. My problem is that first column of the second row contain lot of content(a full screen height), so there is a scroll bar , I want to show all the content without scrolling..., is it possible ???
can i give height to the column ????
|
2009/10/12
|
[
"https://Stackoverflow.com/questions/1553377",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/148449/"
] |
I guess you have your frameset something like this:
```
<frameset rows="100,*,80">
<frame src="f1.htm"/>
<frameset cols="120,*">
<frame src="left.htm"/>
<frame src="right.htm"/>
</frameset>
<frame src="f2.htm"/>
</frameset>
```
Which will look something like this:
```
________________________
| f1.htm |
|______________________|
| | |
| left.htm | right.htm |
|__________|___________|
| f2.htm |
|______________________|
```
If you want the left.htm to fill the entire height in the window, you need to re-structure to this:
```
<frameset cols ="120,*">
<frame src="left.htm"/>
<frameset rows="100,*,80">
<frame src="f1.htm"/>
<frame src="right.htm"/>
<frame src="f2.htm"/>
</frameset>
</frameset>
```
Which will look something like this:
```
________________________
| | f1.htm |
| |___________|
| left.htm | |
| | right.htm |
| |___________|
| | f2.htm |
|__________|___________|
```
|
Setting height to \* should work...
```
<frameset blabla height="*">
```
Bobby
|
48,340,719 |
Found a few versions of this question, such as [Django get environment variables from apache](https://stackoverflow.com/questions/20102620/django-get-environment-variables-from-apache), however the advice I've found so far doesn't seem to work with the latest LTS django (1.11).
I have an apache configuration which holds a number of environment variables, not limited to connection credentials for the DB. Im using this to make my code portable between dev/prod etc.
My apache conf just uses SetEnv to pass in some variables.
I've tried two different styles of approach to use these variables, both seem to suffer from the same issue; it needs to read the settings file before we can write to the environment, and the settings file requires values from the environment.
My two variants are;
```
import os
import django
from django.core.handlers.wsgi import WSGIHandler
from django.core.wsgi import get_wsgi_application
_application = get_wsgi_application()
def application(environ, start_response):
for key in [keys...]:
if environ.get(key):
os.environ[key] = environ.get(key)
return _application(environ, start_response)
```
and
```
import os
import django
from django.core.handlers.wsgi import WSGIHandler
class WSGIEnvironment(WSGIHandler):
def __call__(self, environ, start_response):
for key in [keys...]:
if environ.has_key(key):
print "Key: %s = %s" % (key,environ[key])
os.environ[key] = environ[key]
return super(WSGIEnvironment, self).__call__(environ, start_response)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", 'apiClient.settings')
django.setup(set_prefix=False)
application = WSGIEnvironment()
```
Either way im trying to use the values in settings as;
```
KEY = "thing"
if os.environ.has_key("KEY"):
KEY = os.environ["KEY"]
```
|
2018/01/19
|
[
"https://Stackoverflow.com/questions/48340719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1192158/"
] |
You can't use `SetEnv` as the settings file is evaluated before the first request is handled. Setting environment variables from per request WSGI environ values was always a bad idea and can cause problems, so you shouldn't do that anyway.
Result is that you cannot set environment variables from the Apache configuration file. Set them from the WSGI script file. If they are things that should not be added to a Git repository, create a file on the specific host with the values in some format, and have the WSGI script file read that file from the local host to set them when first loaded and before any Django code is executed.
|
You have to defer initialising the Django app until the first request. Something like this in your wsgi.py:
```
from django.core.wsgi import get_wsgi_application
_application = None
def application(environ, start_response):
global _application
if _application == None:
for key in environ:
if key.startswith('ENV_'):
os.environ[key[4:]] = environ[key]
_application = get_wsgi_application()
return _application(environ, start_response)
```
It's a pity that there appears to be no option in mod\_wsgi to set the initial environment when starting the daemon process, as you can with mod\_fastcgi.
|
48,340,719 |
Found a few versions of this question, such as [Django get environment variables from apache](https://stackoverflow.com/questions/20102620/django-get-environment-variables-from-apache), however the advice I've found so far doesn't seem to work with the latest LTS django (1.11).
I have an apache configuration which holds a number of environment variables, not limited to connection credentials for the DB. Im using this to make my code portable between dev/prod etc.
My apache conf just uses SetEnv to pass in some variables.
I've tried two different styles of approach to use these variables, both seem to suffer from the same issue; it needs to read the settings file before we can write to the environment, and the settings file requires values from the environment.
My two variants are;
```
import os
import django
from django.core.handlers.wsgi import WSGIHandler
from django.core.wsgi import get_wsgi_application
_application = get_wsgi_application()
def application(environ, start_response):
for key in [keys...]:
if environ.get(key):
os.environ[key] = environ.get(key)
return _application(environ, start_response)
```
and
```
import os
import django
from django.core.handlers.wsgi import WSGIHandler
class WSGIEnvironment(WSGIHandler):
def __call__(self, environ, start_response):
for key in [keys...]:
if environ.has_key(key):
print "Key: %s = %s" % (key,environ[key])
os.environ[key] = environ[key]
return super(WSGIEnvironment, self).__call__(environ, start_response)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", 'apiClient.settings')
django.setup(set_prefix=False)
application = WSGIEnvironment()
```
Either way im trying to use the values in settings as;
```
KEY = "thing"
if os.environ.has_key("KEY"):
KEY = os.environ["KEY"]
```
|
2018/01/19
|
[
"https://Stackoverflow.com/questions/48340719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1192158/"
] |
You can't use `SetEnv` as the settings file is evaluated before the first request is handled. Setting environment variables from per request WSGI environ values was always a bad idea and can cause problems, so you shouldn't do that anyway.
Result is that you cannot set environment variables from the Apache configuration file. Set them from the WSGI script file. If they are things that should not be added to a Git repository, create a file on the specific host with the values in some format, and have the WSGI script file read that file from the local host to set them when first loaded and before any Django code is executed.
|
For Django > 1.7 get\_wsgi\_application calls django.setup() which initializes the settings. So if your env vars aren't set at that point you won't see them in the settings.
To get around it, don't actually call get\_wsgi\_application until you're ready. This works for me in wsgi.py:
```
def application(environ, start_response):
os.environ['APPLICATION_ENV'] = environ.get('APPLICATION_ENV', None)
return get_wsgi_application()(environ, start_response)
```
|
48,340,719 |
Found a few versions of this question, such as [Django get environment variables from apache](https://stackoverflow.com/questions/20102620/django-get-environment-variables-from-apache), however the advice I've found so far doesn't seem to work with the latest LTS django (1.11).
I have an apache configuration which holds a number of environment variables, not limited to connection credentials for the DB. Im using this to make my code portable between dev/prod etc.
My apache conf just uses SetEnv to pass in some variables.
I've tried two different styles of approach to use these variables, both seem to suffer from the same issue; it needs to read the settings file before we can write to the environment, and the settings file requires values from the environment.
My two variants are;
```
import os
import django
from django.core.handlers.wsgi import WSGIHandler
from django.core.wsgi import get_wsgi_application
_application = get_wsgi_application()
def application(environ, start_response):
for key in [keys...]:
if environ.get(key):
os.environ[key] = environ.get(key)
return _application(environ, start_response)
```
and
```
import os
import django
from django.core.handlers.wsgi import WSGIHandler
class WSGIEnvironment(WSGIHandler):
def __call__(self, environ, start_response):
for key in [keys...]:
if environ.has_key(key):
print "Key: %s = %s" % (key,environ[key])
os.environ[key] = environ[key]
return super(WSGIEnvironment, self).__call__(environ, start_response)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", 'apiClient.settings')
django.setup(set_prefix=False)
application = WSGIEnvironment()
```
Either way im trying to use the values in settings as;
```
KEY = "thing"
if os.environ.has_key("KEY"):
KEY = os.environ["KEY"]
```
|
2018/01/19
|
[
"https://Stackoverflow.com/questions/48340719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1192158/"
] |
For Django > 1.7 get\_wsgi\_application calls django.setup() which initializes the settings. So if your env vars aren't set at that point you won't see them in the settings.
To get around it, don't actually call get\_wsgi\_application until you're ready. This works for me in wsgi.py:
```
def application(environ, start_response):
os.environ['APPLICATION_ENV'] = environ.get('APPLICATION_ENV', None)
return get_wsgi_application()(environ, start_response)
```
|
You have to defer initialising the Django app until the first request. Something like this in your wsgi.py:
```
from django.core.wsgi import get_wsgi_application
_application = None
def application(environ, start_response):
global _application
if _application == None:
for key in environ:
if key.startswith('ENV_'):
os.environ[key[4:]] = environ[key]
_application = get_wsgi_application()
return _application(environ, start_response)
```
It's a pity that there appears to be no option in mod\_wsgi to set the initial environment when starting the daemon process, as you can with mod\_fastcgi.
|
37,557,284 |
I am trying to increment a value for a key-value in redis, if the value already exists in redis. For instance if we have
```
client.get(key, function checkRedis(err, data){
var redisData = JSON.parse(data);
if(redisData === null){
//do something
}else{
client.incr(redisData.val);
}
});
```
From my understanding, according to the documentation using "incr" should automatically increment that specific value by 1. But i am unable to see this happen successfuly, am i missing something
|
2016/05/31
|
[
"https://Stackoverflow.com/questions/37557284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5213120/"
] |
You need to give `client` the `key` not the value.
I believe the below will do what you need.
```
client.get(key, function checkRedis(err, data){
var redisData = JSON.parse(data);
if(redisData === null){
//do something
}else{
redisData.val++;
client.set(key, redisData);
}
});
```
|
**You need to use the INCR key to increment value in redis**
```
const redisClient = require('ioredis');
const name = 'Bob';
redisClient.incr('id', (err, id) =>
{
redisClient.hmset('user:' + id, 'username', name);
});
```
|
4,305,794 |
I am reading about bases in topology and have encountered the concept of a (local) neighborhood basis. The example they give is for the topology on metric spaces: the set of all open balls around $x$ (or the set of all small open balls around $x$, or all open balls with radius $\frac{1}{n}$ for all $n \in \mathbb{N}$ around $x$). What confuses me is why they only give open balls as examples. Would the set of all closed balls around $x$ also be an example of a neighborhood basis? I think that it satisfies the definition, but I can't find any source mentioning it as an example.
---
**Edit:** (adding the definition)
A *neighbourhood system* $\mathcal{N}(x)$ for a point $x$ is the collection of all neighbourhoods of the point $x$.
A *neighbourhood basis* or *local basis* for a point $x$ is a subset $\mathcal{B} \subseteq \mathcal{N}(x)$, such that for all $V \in \mathcal{N}(x)$, there exists some $B \in \mathcal{B}$ such that $B \subseteq V$. That is, for every neighbourhood $V$, we can find a neighbourhood $B$ in the neihbourhood basis that is contained in $V$.
---
**Edit 2:** (definition of neighbourhood)
If $(X, \mathcal{T})$ is a topological space and $x$ is a point in $X$, a neighbourhood of $x$ is any set $U \in \mathcal{T}$ containing $x$.
|
2021/11/14
|
[
"https://math.stackexchange.com/questions/4305794",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/726980/"
] |
It can be useful to calculate these moments in a general case, invoking [Gamma Function](https://en.wikipedia.org/wiki/Gamma_function)
$$E(X^k)=\int\_0^{\infty} x^k \lambda e^{-\lambda x}dx=\frac{1}{\lambda^k}\int\_0^{\infty}(\lambda x)^k e^{-\lambda x} d(\lambda x)=\frac{\Gamma(k+1)}{\lambda^k}=\frac{k!}{\lambda^k}$$
Thus if you have to calculate, i.e., $E(X^{100})$ you can easy derive the solution... instead of doing 100 times by part you integral
|
The notation being used here is an alternate way of writing
$$u = x^2, \quad du = 2x \, dx, \\
dv = \lambda e^{-\lambda x} dx, \quad v = -e^{-\lambda x}.$$
You will notice that with this definition of $v$, we simply have $$d(-e^{-\lambda x}) = dv = \lambda e^{-\lambda x} \, dx,$$ and substituting this into the first line gives
$$\int\_{x=0}^\infty x^2 d(-e^{-\lambda x}) = \int\_{x=0}^\infty x^2 \lambda e^{-\lambda x} \, dx.$$
|
869,178 |
In Nginx we can return a specific status code to URL prefix like this.
`location /api {
return 200;
}`
How can we achieve the same in Haproxy?.
Gone through Haproxy ACL but couldn't find any.
|
2017/08/17
|
[
"https://serverfault.com/questions/869178",
"https://serverfault.com",
"https://serverfault.com/users/281864/"
] |
This can be accomplished by using a lua response script.
I already use one to set the CORS headers for the preflight response.
My rule is the following:
```
global
...
lua-load /etc/haproxy/200.lua
frontend
bind ...
...
use_backend http_200 if ...
backend http_200
http-request use-service lua.200-response
```
Lua script in `/etc/haproxy/200.lua`:
```
# 200.lua
core.register_service("200-response", "http", function(applet)
local response = ""
applet:set_status(200)
applet:add_header("Content-Length", "0")
applet:start_response()
applet:send(response)
end)
```
|
For completeness, from version 2.2 you can return dynamic content like this
```
http-request return status 200 content-type "text/plain" lf-string "Hello"
```
More in [docs](https://cbonte.github.io/haproxy-dconv/2.5/configuration.html#4.2-http-request%20return).
|
21,182,321 |
At the moment i have a query which counts the number of records dependent on country, and gives me a list something like:
* UK = 400
* Spain = 350
* etc...
I have now added in another coloumn for language as some countries have different languages e.g. Switzerland\_Italian.
What would be the best way to amend my query so that if the country has different languages(as some don't) it will count these seperately in my list, so it would look something like:
* UK = 400
* Spain = 350
* Switzerland = 200
* Switzerland\_Italian = 50
Would this need a subquery? The query i have at the moment is, i have added in the new lang coloumn:
```
SELECT
COUNT(*) AS `count`,
`region`,
`lang`,
DATE(NOW()) AS `week_ending`
FROM
mydata.table
WHERE `date` > DATE_ADD(DATE(NOW()), INTERVAL - 1 WEEK)
AND `date` < DATE(NOW())
GROUP BY `region`,
DATE(NOW()) ;
```
|
2014/01/17
|
[
"https://Stackoverflow.com/questions/21182321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2739911/"
] |
You would have to GROUP BY both region and lang, like this:
```
SELECT COUNT(*) as `count`,`region`, `lang`, DATE(NOW()) as `week_ending`
FROM mydata.table
WHERE `date` > DATE_ADD(DATE(NOW()), INTERVAL -1 WEEK) AND `date` < DATE(NOW())
GROUP BY `region`, `lang`, DATE(NOW());
```
|
How about this
```
SELECT
COUNT(*) AS `count`,
CONCAT( `region`,'_',`lang`),
`region`,
`lang`,
DATE(NOW()) AS `week_ending`
FROM
mydata.table
WHERE `date` > DATE_ADD(DATE(NOW()), INTERVAL - 1 WEEK)
AND `date` < DATE(NOW())
GROUP BY `region`,`lang`,
DATE(NOW()) ;
```
|
36,865,742 |
On my project i have wordpress custom field data from mysql :
```
---------------------------------------------------
id | post_id | meta_key | meta_value
---------------------------------------------------
1 | 200 | age_min | 5
2 | 200 | age_max | 8
3 | 399 | ... | ...
```
My table structure
```
id => aut_increment
meta_key => varchar(255)
meta_value => longtext
```
From my sql script i have to find childs between 'age\_min and age\_max' and childs number :
```
SELECT DISTINCT p.ID
, a.meta_value as nbrmin, b.meta_value as nbr_enfants_min , c.meta_value as age_min, d.meta_value as age_max
FROM `6288gjvs_posts` as p
LEFT JOIN 6288gjvs_postmeta as a ON a.post_id = p.ID
LEFT JOIN 6288gjvs_postmeta as b ON b.post_id = p.ID
LEFT JOIN 6288gjvs_postmeta as c ON c.post_id = p.ID
LEFT JOIN 6288gjvs_postmeta as d ON d.post_id = p.ID
WHERE p.post_type = 'product' AND post_status = 'publish'
AND a.meta_key = 'childs_min_number'
AND a.meta_value <= 2
AND b.meta_key = 'childs_max_number'
AND b.meta_value >= 2
AND c.meta_key = 'age_min'
AND c.meta_value = 1
AND d.meta_key = 'age_max'
AND d.meta_value >= 10
```
When i launch this query, this not working properly, because meta\_value type is a longtext and my php variables ( $this->age\_min, $this->age\_max ) are integers, so i cannot compare those 2 different type ?
I tried to convert like this with no luck :
```
... CONVERT(a.meta_value, DECIMAL) ...
```
as mentioned from this site : [Mysql conversion functions](http://www.geeksengine.com/database/single-row-functions/conversion-functions.php#p1-5)
Anyone can help me please ?
Thank you.
|
2016/04/26
|
[
"https://Stackoverflow.com/questions/36865742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Using ajax you can call a controller action and return it's response to a particular `div`.
Empty `div`:
```
<div class="row" id="div3">
</div>
```
Ajax to display html in empty `div`:
```
function performSearch(searchCriteria) {
//get information to pass to controller
var searchInformation = JSON.stringify(**your search information**);
$.ajax({
url: '@Url.Action("Search", "ControllerName")',//controller name and action
type: 'POST',
data: { 'svm': searchInformation } //information for search
})
.success(function (result) {
$('#div3').html(result); //write returned partial view to empty div
})
.error(function (xhr, status) {
alert(status);
})
}
```
|
So, say you have your View with PartialView, which have to be updated by button click:
```
<div class="target">
@{ Html.RenderAction("UpdatePoints");}
</div>
<input class="button" value="update" />
```
There are some ways to do it. For example you may use jQuery:
```
<script type="text/javascript">
$(function(){
$('.button')click(function(){
$.post('@Url.Action("PostActionToUpdatePoints", "Home")').always(function(){
$('.traget').Load('/Home/UpdatePoints');
})
});
});
</script>
```
PostActionToUpdatePoints is your Action with [HttpPost] attribute, which you use to update points
If you use logic in your action UpdatePoints() to update points, maybe you forgot to add [HttpPost] attribute to it:
```
[HttpPost]
public ActionResult UpdatePoints()
{
ViewBag.points = _Repository.Points;
return PartialView("UpdatePoints");
}
```
|
36,865,742 |
On my project i have wordpress custom field data from mysql :
```
---------------------------------------------------
id | post_id | meta_key | meta_value
---------------------------------------------------
1 | 200 | age_min | 5
2 | 200 | age_max | 8
3 | 399 | ... | ...
```
My table structure
```
id => aut_increment
meta_key => varchar(255)
meta_value => longtext
```
From my sql script i have to find childs between 'age\_min and age\_max' and childs number :
```
SELECT DISTINCT p.ID
, a.meta_value as nbrmin, b.meta_value as nbr_enfants_min , c.meta_value as age_min, d.meta_value as age_max
FROM `6288gjvs_posts` as p
LEFT JOIN 6288gjvs_postmeta as a ON a.post_id = p.ID
LEFT JOIN 6288gjvs_postmeta as b ON b.post_id = p.ID
LEFT JOIN 6288gjvs_postmeta as c ON c.post_id = p.ID
LEFT JOIN 6288gjvs_postmeta as d ON d.post_id = p.ID
WHERE p.post_type = 'product' AND post_status = 'publish'
AND a.meta_key = 'childs_min_number'
AND a.meta_value <= 2
AND b.meta_key = 'childs_max_number'
AND b.meta_value >= 2
AND c.meta_key = 'age_min'
AND c.meta_value = 1
AND d.meta_key = 'age_max'
AND d.meta_value >= 10
```
When i launch this query, this not working properly, because meta\_value type is a longtext and my php variables ( $this->age\_min, $this->age\_max ) are integers, so i cannot compare those 2 different type ?
I tried to convert like this with no luck :
```
... CONVERT(a.meta_value, DECIMAL) ...
```
as mentioned from this site : [Mysql conversion functions](http://www.geeksengine.com/database/single-row-functions/conversion-functions.php#p1-5)
Anyone can help me please ?
Thank you.
|
2016/04/26
|
[
"https://Stackoverflow.com/questions/36865742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
jQuery will help you with it!
Try to handle submit button onclick event like this:
```
$("#yourButtonId").click(function()
{
$.ajax({
type: "POST",
url: "/yourUrl", //in asp.net mvc using ActionResult
data: data,
dataType: 'html',
success: function (result) {
//Your result is here
$("#yourContainerId").html(result);
}
});
});
```
|
So, say you have your View with PartialView, which have to be updated by button click:
```
<div class="target">
@{ Html.RenderAction("UpdatePoints");}
</div>
<input class="button" value="update" />
```
There are some ways to do it. For example you may use jQuery:
```
<script type="text/javascript">
$(function(){
$('.button')click(function(){
$.post('@Url.Action("PostActionToUpdatePoints", "Home")').always(function(){
$('.traget').Load('/Home/UpdatePoints');
})
});
});
</script>
```
PostActionToUpdatePoints is your Action with [HttpPost] attribute, which you use to update points
If you use logic in your action UpdatePoints() to update points, maybe you forgot to add [HttpPost] attribute to it:
```
[HttpPost]
public ActionResult UpdatePoints()
{
ViewBag.points = _Repository.Points;
return PartialView("UpdatePoints");
}
```
|
36,865,742 |
On my project i have wordpress custom field data from mysql :
```
---------------------------------------------------
id | post_id | meta_key | meta_value
---------------------------------------------------
1 | 200 | age_min | 5
2 | 200 | age_max | 8
3 | 399 | ... | ...
```
My table structure
```
id => aut_increment
meta_key => varchar(255)
meta_value => longtext
```
From my sql script i have to find childs between 'age\_min and age\_max' and childs number :
```
SELECT DISTINCT p.ID
, a.meta_value as nbrmin, b.meta_value as nbr_enfants_min , c.meta_value as age_min, d.meta_value as age_max
FROM `6288gjvs_posts` as p
LEFT JOIN 6288gjvs_postmeta as a ON a.post_id = p.ID
LEFT JOIN 6288gjvs_postmeta as b ON b.post_id = p.ID
LEFT JOIN 6288gjvs_postmeta as c ON c.post_id = p.ID
LEFT JOIN 6288gjvs_postmeta as d ON d.post_id = p.ID
WHERE p.post_type = 'product' AND post_status = 'publish'
AND a.meta_key = 'childs_min_number'
AND a.meta_value <= 2
AND b.meta_key = 'childs_max_number'
AND b.meta_value >= 2
AND c.meta_key = 'age_min'
AND c.meta_value = 1
AND d.meta_key = 'age_max'
AND d.meta_value >= 10
```
When i launch this query, this not working properly, because meta\_value type is a longtext and my php variables ( $this->age\_min, $this->age\_max ) are integers, so i cannot compare those 2 different type ?
I tried to convert like this with no luck :
```
... CONVERT(a.meta_value, DECIMAL) ...
```
as mentioned from this site : [Mysql conversion functions](http://www.geeksengine.com/database/single-row-functions/conversion-functions.php#p1-5)
Anyone can help me please ?
Thank you.
|
2016/04/26
|
[
"https://Stackoverflow.com/questions/36865742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
You can do it with ajax.
First, change your html.beginform to ajax.beginform in your view and add div id into **UpdateTargetId** that you want to change contents. After updating first partial with ajax.beginform, you can update other partialviews with ajax.beginform's **"OnSuccess"** function. You have to add update function like that:
```
@using (Ajax.BeginForm("YourAction", "YourController",
new { /*your objects*/ }, new AjaxOptions { HttpMethod = "POST", InsertionMode = InsertionMode.Replace,
UpdateTargetId = "ChangeThisPart", OnSuccess = "OnSuccessMethod" }))
{
/*your code*/
}
<script>
function OnSuccessMethod() {
$("#YouWantToChangeSecondDivID").load('/YourController/YourAction2');
$("#YouWantToChangeThirdDivID").load('/YourController/YourAction3');
};
</script>
```
Then in your controller, return a partial view to refresh your view part that you entered it's ID in UpdateTargetId value:
```
public ActionResult YourControllerName(YourModelType model)
{
...//your code
return PartialView("_YourPartialViewName", YourViewModel);
}
```
**Note:** Don't forget to add reference to "jquery.unobtrusive-ajax.min.js" in your view while using ajax.
|
So, say you have your View with PartialView, which have to be updated by button click:
```
<div class="target">
@{ Html.RenderAction("UpdatePoints");}
</div>
<input class="button" value="update" />
```
There are some ways to do it. For example you may use jQuery:
```
<script type="text/javascript">
$(function(){
$('.button')click(function(){
$.post('@Url.Action("PostActionToUpdatePoints", "Home")').always(function(){
$('.traget').Load('/Home/UpdatePoints');
})
});
});
</script>
```
PostActionToUpdatePoints is your Action with [HttpPost] attribute, which you use to update points
If you use logic in your action UpdatePoints() to update points, maybe you forgot to add [HttpPost] attribute to it:
```
[HttpPost]
public ActionResult UpdatePoints()
{
ViewBag.points = _Repository.Points;
return PartialView("UpdatePoints");
}
```
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.