text:
Q: Tab commands in Adobe Brackets? Sublime has the ability to enter tags when typing the unbracketed word + TAB. Is there any way to recreate this functionality in Brackets? I went through their entire extension list but didn't see anything for this purpose.

A: What u want is "emmet" extension. It's actually in the extension list.


text:
Q: android:attr/fontStyle not found when i run ./gradlew assembleRelease on my react android project, i keep getting the following error:
    A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > Android resource linking failed
     /root/.gradle/caches/transforms-2/files-2.1/6da249295a8c8ecbd4d1ab0ef0c0da5a/core-1.5.0-alpha04/res/values/values.xml:143:5-174:25: AAPT: error: resource android:attr/fontStyle not found.

     /root/.gradle/caches/transforms-2/files-2.1/6da249295a8c8ecbd4d1ab0ef0c0da5a/core-1.5.0-alpha04/res/values/values.xml:143:5-174:25: AAPT: error: resource android:attr/font not found.

     /root/.gradle/caches/transforms-2/files-2.1/6da249295a8c8ecbd4d1ab0ef0c0da5a/core-1.5.0-alpha04/res/values/values.xml:143:5-174:25: AAPT: error: resource android:attr/fontWeight not found.

     /root/.gradle/caches/transforms-2/files-2.1/6da249295a8c8ecbd4d1ab0ef0c0da5a/core-1.5.0-alpha04/res/values/values.xml:143:5-174:25: AAPT: error: resource android:attr/fontVariationSettings not found.

     /root/.gradle/caches/transforms-2/files-2.1/6da249295a8c8ecbd4d1ab0ef0c0da5a/core-1.5.0-alpha04/res/values/values.xml:143:5-174:25: AAPT: error: resource android:attr/ttcIndex not found.

It builds fine of i do a assembeDebug
Here is some of my gradle build settings
 buildToolsVersion = "29.0.2"
        minSdkVersion = 16
        compileSdkVersion = 29
        targetSdkVersion = 29
        ext.kotlin_version = '1.4.10'

multiDexEnabled true

release {
            signingConfig signingConfigs.release
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }

apply from: file("../../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesAppBuildGradle(project)
buildscript {
    ext.kotlin_version = '1.4.10'
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
    }
}
repositories {
    mavenCentral()
}

A: run this command:
react-native bundle --platform android --dev false --entry-file index.js --bundle-output android/app/src/main/assets/index.android.bundle --assets-dest android/app/src/main/res --verbose
and then delete project_root/android/app/src/main/raw + drawable-.. folders.
After that build your release APK.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pagebale & sort by COUNT() with other table - JPA I've got this query
SELECT t.id,t.title,count(k.id) as likes
FROM topics t
LEFT JOIN topic_like k on t.id = k.topic_id
group by t.id, t.title
ORDER BY likes desc ;

When I try to convert it to the JPQL, I do it like this but I gut some issues
@Query("SELECT p,count(k.id) as likes FROM TopicJpa p " +
            "LEFT JOIN TopicLikeJpa k " +
            "GROUP BY p ORDER BY COUNT(likes)")
    Page<TopicJpa> getAllTopicsWithLikeCountsSort(Pageable pageable);

A: The query should be:
SELECT p, count(k) as likes
FROM TopicJpa p
         LEFT JOIN p.topicLikeJpa k
GROUP BY p
ORDER BY likes

You can return the result as a Page<Object[]>:
@Query("...")
Page<Object[]> getAllTopicsWithLikeCountsSort(Pageable pageable);

Page<Object[]> page = repository.getAllTopicsWithLikeCountsSort(...);
List<Object[]> resultList = page.getContent();
for(Object[] row : resultList) {
   TopicJpa topic = (TopicJpa) row[0];
   Long counter = (Long) row[1];
}

Or, you can create an interface with two fields:
interface TopicWithCounter {
    TopicJpa getTopic();
    Long getLikes();
}

and use it as the page type:
@Query("...")
Page<TopicWithCounter> getAllTopicsWithLikeCountsSort(Pageable pageable);

If you don't care about the count for each topic, you can omit it from the select clause and return Page<TopicJpa> instead:
@Query("SELECT p FROM TopicJpa p LEFT JOIN p.topicLikeJpa k GROUP BY p ORDER BY COUNT(k)")
Page<TopicJpa> getAllTopicsWithLikeCountsSort(Pageable pageable);


text:
Q: projectRaster consuming too much memory I'm doing some spatial stuff in R and out of the blue some of my code will no longer work on a computer that I've been using for years, specifically because it's "running out of memory."
## Raster going in
xx <- raster(fatNames[[i]])
xx
class       : RasterLayer
dimensions  : 5160, 14436, 74489760  (nrow, ncol, ncell)
resolution  : 0.008333333, 0.008333333  (x, y)
extent      : -172.3, -52, 23.5, 66.5  (xmin, xmax, ymin, ymax)
coord. ref. : +proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0
data source : D:\Dropbox\wintor_aux\Results\myluFatReq_100_2_fat.inf.tif
names       : myluFatReq_100_2_fat.inf
values      : 0.1831425, 3.449095  (min, max)

## transform
x.rast <- projectRaster(xx,crs = CRS("+init=epsg:2955"))

Error: can not adequate vector of 4.2Gb.
Now I know this is a decent sized raster (Input raster size: 75.5 MB) however the machine has 32Gb of RAM, no other programs are running and I still swamp the memory. I've done things like this hundreds of times over the years and to the best of my knowledge nothing on the machine has changed since I did this last about a month ago.
I've tried restarting the session, restarting the computer and have googled around a bit but I still haven't had any luck in trying to trace down the issues. When I try the same code block on a machine with 1/2 the RAM I'm able to run it no problem (using ~ 8Gb ram max). Does anyone have any suggestions as to how I can chase this down?
> sessionInfo()
R version 3.5.1 (2018-07-02)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)

Matrix products: default

locale:
[1] LC_COLLATE=English_New Zealand.1252  LC_CTYPE=English_New Zealand.1252
[3] LC_MONETARY=English_New Zealand.1252 LC_NUMERIC=C
[5] LC_TIME=English_New Zealand.1252

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] raster_2.6-7         rgdal_1.3-3          sp_1.3-1             sf_0.6-3
[5] RevoUtils_11.0.1     RevoUtilsMath_11.0.0

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.18    lattice_0.20-35 class_7.3-14    grid_3.5.1      spData_0.2.9.0
 [6] DBI_1.0.0       magrittr_1.5    e1071_1.7-0     units_0.6-0     tools_3.5.1
[11] yaml_2.2.0      compiler_3.5.1  classInt_0.2-3

A: You should first update the raster package to its current (CRAN) version. That might fix this. If not, this is probably a corner-case that you should be able to work-around by setting the memory parameters to a lower value. In the current version you could do rasterOptions(memfrac=.3). In the current and older versions you may try rasterOptions(maxmemory=1e+08)
By the way, your transformation to +proj=utm +zone=11 (please do not use espg codes in examples) seems rather questionable given that the input data has a longitude span of (172.3 - 52) = 120 degrees --- UTM is valid for a span of about 6 degrees.


text:
Q: Combine audio and video to file in Gstreamer On my Raspberry Pi i create a h.264 timelapse video from jpeg in gestreamer.
sudo gst-launch-1.0 multifilesrc location=/home/pi/Timelapse/20160820/image_%04d.jpg index=0 \
caps="image/jpeg,framerate=\(fraction\)24/1" ! \
jpegdec ! \
queue ! \
omxh264enc target-bitrate=15000000 control-rate=variable ! \
video/x-h264,width=1920,height=1080,framerate=24/1,profile=high ! \
h264parse ! \
mp4mux faststart=true ! \
filesink location=/home/pi/Timelapse/20160820/1.mp4

This works pretty good.
I also want to add a audio to the timelapse video. How can i use a mp3 file as background music and save combined file to disk?
Thanks.


text:
Q: Error: taking address of temporary I know that this question was already asked a lot but non of the answers could help me with my specific problem.
I get the famous "taking adress of temporary" error. And as far as I understood that's because I am trying to convert a temporary object to a pointer.
But does anyone here has a solution to how I can fix this here?
My code in that the error occurs is the following:
newGame = &MenuOption(optionNewGame, text_new_game.width, 2, 0);

The declaration of newGame looks like this:
MenuOption *newGame;

An the error looks like this:
1>  c:/path/to/project/MainMenu.h:27:65: error: taking address of temporary [-fpermissive]
1>     newGame = &MenuOption(optionNewGame, text_new_game.width, 2, 0);
1>                                                                   ^

A: You are creating a temporary object of your MenuOption class. Then you store the address of this temporary object in newGame. Once the control block is left, the temporary object will be deleted and your pointer becomes a 'dangling pointer'.
Solutions:

*

*MenuOption newGame(optionNewGame, text_new_game.width, 2, 0);

*newGame = new MenuOption(optionNewGame, text_new_game.width, 2, 0);

*use unique_ptr:
std::unique_ptr< MenuOption> newGame;
newGame.reset( new MenuOption(optionNewGame, text_new_game.width, 2, 0));


text:
Q: In Javascript, how do I use .filter to return objects that have a property that contains a string? I have the following code that returns everything I expect it to
let discs = Discrepancies.filter(function(disc) {
  return disc.defect.toLowerCase() == def.id.toLowerCase();
});

however, now I would like to change this to return all results that contain a substring. For example:
disc.defect.toLowerCase = 'loose fastener'

and I want to return all def.id.toLowerCase() if it contains the substring 'loose'.
How do I accomplish this?
I tried include but it doesn't seem to work for me. I'm using IE 11.


text:
Q: Optimize Database Structure The service I created will increase the number of API call, actually we only insert on our log table arround 200k entries every days.
Soon we will need to support 1-2 Millions entries each day on our Database.
Each API call = One entrie on the DB.
How can I increase the performance of the table logs_fb ?
What is the number maximum of rows on a table ?

A: For multi-million row tables, you really need to consider normalizing columns wherever practical.  For example, there may be only a few thousand distinct user_agent values, you you are saving dozens or hundreds of bytes for multiple copies.  using a SMALLINT UNSIGNED linked to another table would shrink that to 2 bytes.
Why worry about space?  It has some impact on speed.  It forestalls running out of disk space.
Be consistent, and use reasonable datatypes:  If you won't have more than, say, 64K users, declare user_id in both tables as SMALLINT UNSIGNED.
What language needs 255 characters to describe?  Consider using an ENUM.
IP addresses, even IPv6, can be compressed into BINARY(16) (16 bytes) instead of the up-to-39 you currently have.  (And 255 is overkill.)
20 INSERTs per second is no problem for MySQL.
What is the API hitting?  A web server?  REST?  Java?  Can that handle 20/second?
What will the PRIMARY KEY be?  What SELECTs will be applied to the dataset?  These need to be discussed to talk about indexes, and whether you will have performance problems when reading.
Max number of records?  You will run out of disk space before you hit any database limit.  I think there is a limit of 64TB.  I've seen a billion-row table in action.
Do the math.  When will you run out of disk space?  Will you drop "old" data after some period of time?  If so, let's talk about an efficient way to do that -- else you will come back with a problem of a huge DELETE.


text:
Q: How to share image to facebook from fragment I'm using Facebook SDK and I want to know how to use share in fragment
public class FullScreenImageAdapter extends PagerAdapter {

private Activity _activity;
private ArrayList<String> _imagePaths;
private LayoutInflater inflater;
public CallbackManager callbackManager;
public LoginManager loginManager;
// constructor
public FullScreenImageAdapter(Activity activity,
        ArrayList<String> imagePaths) {
    this._activity = activity;
    this._imagePaths = imagePaths;
}

@Override
public int getCount() {
    return this._imagePaths.size();
}

@Override
public boolean isViewFromObject(View view, Object object) {
    return view == ((RelativeLayout) object);
}

@Override
public Object instantiateItem(ViewGroup container, int position) {
    TouchImageView imgDisplay;
    Button btnClose;

    inflater = (LayoutInflater) _activity
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View viewLayout = inflater.inflate(R.layout.full_photo, container,
            false);

    FacebookSdk.sdkInitialize(_activity.getApplicationContext());
    callbackManager = CallbackManager.Factory.create();
    List<String> permissionNeeds = Arrays.asList("publish_actions");
    //this loginManager helps you eliminate adding a LoginButton to your UI
    LoginManager manager = LoginManager.getInstance();
    manager.logInWithPublishPermissions(this, permissionNeeds);*// It Problem

It Problem  manager.logInWithPublishPermissions(this, permissionNeeds) cannot resolve method
And problem super.onActivityResult it cannot reslove
 @Override
protected void onActivityResult(final int requestCode, final int resultCode, final Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    callbackManager.onActivityResult(requestCode, resultCode, data);

}

Plese help me   or solve solution here Sorry I'm Weak  English Language


text:
Q: How to compare 2 csv files, perform operations and output into a new csv file I don't have any idea on how to compare 2 csv files (old.csv, change.csv) and after performing different operations (add, update,delete) a new.csv file will produce. I just need an Idea on how to do this. I was able to read and write a file using FileReader and Writer. I don't know how to compare files and perform operations. I should use an array for data-entries.
My csv files contains column:
Old.csv
CODE  NAME  ADDRESS  NUMBER
0001  John  USA      1234

Change.csv
CHANGE  CODE  NAME   ADDRESS  NUMBER
ADD     0002  Shane  Germany  5678
UPDATE  0001         Canada

New.csv
CODE   NAME  ADDRESS  NUMBER
0001   John  Canada   1234
0002   Shane Germany  5678

Please help for ideas. Thanks in advance.

A: It looks like, here your name column is the primary key between 2 csv files, while reading the CSV file you can create a hashmap of  type, where Name=Name coulmn value and Data is the whole object. later while traversing each change CSV record you can have switch statement to handle change and in each case you can manage individual updates to hashmap. After successful traversal your hashmap would contain required updated instance, which you can traverse and covert to new csv.

A: For such a task i suggest to use a csv parser like opencsv or supercsv
and make use of a data class.
Below is an example using opencsv:
Create a class which looks something like this:
    public class Person {

    private String code;
    private String name;
    private String address;
    private String number;

    public Person(String code, String name, String address, String number) {
        this.code = code;
        this.name = name;
        this.address = address;
        this.number = number;
    }

    public String geCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }
}

and use above class as data holder in your application to compare the two files and create a new csv file
    import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class NewClass1 {
    public static void main(String[] args) {
        try {
            String oldFile = "Old.csv";
            String changeFile = "Change.csv";
            String newFile = "New.csv";
            Map<String,Person> personsList = readOldCsv(oldFile);
            personsList = getChangesfromChangeCsv(changeFile,personsList);
            writeNewCsvFile(newFile,personsList);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    //read your old csv file line by line and create an object person
    //and put it in a map with code as key and person itself as value
    //here assumed that your files are tab separeted '\t';
    //if not change to ';' or ',' according to your separator
    public static Map<String,Person> readOldCsv(String fileName) throws IOException{
        Map<String,Person> personsList = new HashMap<>();
        String [] nextLine;
        CSVReader reader = new CSVReader(new FileReader(fileName), '\t' ,'\'', 1);
        while ((nextLine = reader.readNext()) != null) {
            personsList.put(nextLine[0],new Person(nextLine[0], nextLine[1], nextLine[2], nextLine[3]));
        }
        return personsList;
    }
    // read your change csv file and add or update persons depending on the change column
    public static Map<String,Person> getChangesfromChangeCsv(String fileName, Map<String,Person> personsList) throws IOException{
        String [] nextLine;
        CSVReader reader = new CSVReader(new FileReader(fileName), '\t' ,'\'', 1);
        while ((nextLine = reader.readNext()) != null) {
            switch(nextLine[0].toLowerCase()){
                case "add":
                    personsList.put(nextLine[1],new Person(nextLine[1], nextLine[2], nextLine[3], nextLine[4]));
                case "update":
                    personsList.get(nextLine[1]).setName(!nextLine[2].isEmpty()? nextLine[2]:personsList.get(nextLine[1]).getName());
                    personsList.get(nextLine[1]).setAddress(!nextLine[3].isEmpty()? nextLine[3]:personsList.get(nextLine[1]).getAddress());
                    personsList.get(nextLine[1]).setNumber(!nextLine[4].isEmpty()? nextLine[4]:personsList.get(nextLine[1]).getNumber());
                default:
                    System.out.println("unexpected entry");
            }
        }
        // use TreeMap to get a map sorted by key
        return new TreeMap<>(personsList);
    }

    //write the values of the map into a new csv file
    private static void writeNewCsvFile(String filename,Map<String,Person> personsList) throws IOException {
        CSVWriter writer = new CSVWriter(new FileWriter(filename,false), '\t',CSVWriter.NO_QUOTE_CHARACTER);
        for(Person p : personsList.values() ){
            String[] entries = {p.geCode(),p.getName(),p.getAddress(),p.getNumber()};
            writer.writeNext(entries);
        }
        writer.close();
    }
}


text:
Q: Pandas how to merge duplicates rows into one but without modifying string columns I got problems when processing data in an xlsx file. my leader told me first to merge the same rows' values according to uid. then I should get the sum of "content post volume", "views" and "exploration volume" according to the column "Account type" which consists of types "content" and "social".
For example, there are two rows recording the data of uid 1680260000, now merge them into one. the later three columns should add, turn into 5364, 3710029, and 300478. But don't modify the former three columns. The user_level should keep it as F2.(order like F1, F2, F3, F4...prefer the front value)
uid          user_level    Account type   content post volum  exploration volum    Views
1680260000  F2                content          112                   934318            118
2209220000  F1                social           628                  147623896     20160351
1680260000  F5                content          5252                  2775711        300290
5390800000  F3                content          127                   1235530          8554
6017200000  F2                social           142                    649046         43144
7054610000  F2                social           23                    1226520        232074
1682390000  F2                content          1162                 18025639           722
3136670000  F2                content          6                    2123571         189379
3136670000  F6                content          0                         6              0
5393860000  F2                social           60                    3246476           17
6017200000  F3                content          677                   8855471        277229
6017200000  F2                social           737                  11854463             0
1685250000  F2                content          96                    2211002          5942

The expected result:
uid          user_level    Account type   content post volum    exploration volum    Views
1680260000  F2                content         5364                  3710029       20160469
2209220000  F1                social           628                  147623896     20160351
5390800000  F3                content          127                   1235530          8554
6017200000  F2                social           1556                  21358980       320373
7054610000  F2                social           23                    1226520        232074
1682390000  F2                content          1162                 18025639          722
3136670000  F2                content          6                    2123577         189379
5393860000  F2                social           60                    3246476           17
1685250000  F2                content          96                    2211002          5942

Now the problem is if I use df.groupby("uid").sum(), the column "Account type"(which type is string) will add together too. This isn't what I want, because later I need to extract data depending on it. For example, after I merge the rows with duplicated uid, I need to get rows which "Account type" is in ["F0", "F1", "F2"]. But groupby will make cell value turn to "F1F3", "F4F1" so it's hard to distinguish it.  I did try to split the string when extracting, such as
file[file.Account_social_type.str.split("F").isin(["1", "2", "3"])]
ps: after df.str.split("F"), the "F1F3" will turn to ["1", "3"]

but somehow at this time .str.split("F") won't work for every cell but the whole column!
So in the last, I use a stupid method. First I use
taruid = file[file.uid.duplicated(keep="first")].uid.to_list()
# somehow this statement still left repeated value in list ^
taruid = list(set(taruid))

to get all repeated uid. Then use
def changeOne(rows : pd.DataFrame):
    rows = rows.sort_values(by = "F_level")
    rows.content_post_volume.iloc[0] = rows["content_post_volume"].sum()/(92)
    rows.views.iloc[0] = rows["views"].sum()/92
    rows.exploration_volume.iloc[0] = rows["exploration_volume"].sum()/92
    return rows

replaceOne : pd.DataFrame = pd.DataFrame()
for items in taruid:
    goals = file[file.uid == items]
    replaceOne = replaceOne.append(changeOne(goals.copy()).iloc[0])

to get the sum value of specified columns and store it in the first rows. in the last use
file = file.drop_duplicates(subset = "uid", keep=False)
# drop all repeated rows
file = pd.concat([file, replaceOne], axis=0, ignore_index=True)

to get the final integrated data. And the flaws are very significant, near 1500 data cost 3s. There must be a much easier and more efficient method to use groupby or some advanced pandas function to slove this problem.
WHAT I WANNA ask is, how can we merge/add duplicated/specified rows without modify string column or the columns I specified.
I spend half a day to optimize this but I failed, really appreciate it if you guys can figure it out.

A: The expected format is unclear, but you can use different functions to aggregate the data.
Let's form comma separated strings of the unique values for "user_level" and "Account type":
string_agg = lambda s: ','.join(dict.fromkeys(s))

out = (df.groupby('uid', as_index=False)
         .agg({'user_level': string_agg, 'Account type': string_agg,
               'content post volum': 'sum',
       'exploration volum': 'sum', 'Views': 'sum'})
      )

Output:
          uid user_level    Account type  content post volum  exploration volum     Views
0  1680260000      F2,F5         content                5364            3710029    300408
1  1682390000         F2         content                1162           18025639       722
2  1685250000         F2         content                  96            2211002      5942
3  2209220000         F1          social                 628          147623896  20160351
4  3136670000      F2,F6         content                   6            2123577    189379
5  5390800000         F3         content                 127            1235530      8554
6  5393860000         F2          social                  60            3246476
7  6017200000      F2,F3  social,content                1556           21358980    320373
8  7054610000         F2          social                  23            1226520    232074

For the demo, here is an alternative aggregation function to count the duplicates:
from collections import Counter
string_agg = lambda s: ','.join([f'{k}({v})' if v>1 else k for k,v in Counter(s).items()])

Output:
          uid user_level       Account type  content post volum  exploration volum     Views
0  1680260000      F2,F5         content(2)                5364            3710029    300408
1  1682390000         F2            content                1162           18025639       722
2  1685250000         F2            content                  96            2211002      5942
3  2209220000         F1             social                 628          147623896  20160351
4  3136670000      F2,F6         content(2)                   6            2123577    189379
5  5390800000         F3            content                 127
6  5393860000         F2             social                  60            3246476        17
7  6017200000   F2(2),F3  social(2),content                1556           21358980    320373
8  7054610000         F2             social                  23            1226520    232074

A: df = df.groupby(['uid','Account type', 'user_level '])[['content post volume', 'exploration volume', 'views']].sum()
df2 = df.groupby(['uid','Account type'])[['content post volume', 'exploration volume', 'views']].sum()
df = df.reset_index()
df = df.drop_duplicates('uid')
df = df[['uid', 'Account type', 'user_level ']]
df = df.merge(df2, on=['uid'])
df

output


text:
Q: Railties - When to use After reading some posts about the railties, I've didn't understand if i should only create railsties for gem/plugins that direct interfere with the rails initialization (e.g. create a generator, change some configuration) or if I should also use it for gem/plugins that only add functionality to rails (e.g. include some module in ActionView::Base or ActiveRecordBase).
Any idea or suggestion about this?

A: You can do both and more with railties.  There are hooks that a railtie can implement that would create a generator or do something on rails boot up.  People also use railties to ship rails specific gems.  They don't really "direct interfere" (as you said), they insert themselves in a initialization chain.  You can read more about the init chain here.  Item 2.10 is where the custom railties (ie: your code) gets invoked (at least for startup).


text:
Q: How can I move a geom_line behind the scatter plot? My dataframe has 3 columns (temperature plus two estimates of the same variable using different methods e.g. length).  I want to plot one as a curve and one as a scatter, which I can do.  But the line is in front of the scatter and looks ugly.  I've tried moving the line to first thing given to ggplot but it doesn't help.
EDIT: example of my data using random numbers.  df = data.frame(temp = c(0.1,0.5,0.6,0.9,1.6),var1 = c(1,2,3,4,5), var2 = c(5,4,3,2,1))
EDIT: more detail.  Var1 and var2 are different estimates of the same variable, estimated using different methods.  E.g. height.  And I want to visualise them against temperature, with var1 as a line, and var2 as points.  But I need the line to be behind the points which I think looks better.
Below is what I've tried, the difference being the order of scatter/line passed to ggplot2.  But the line doesn't go behind the points.
p = ggscatter(df,x="temp",y="var2") +
  geom_line(data = df, aes(x = temp, y = var1), color = "blue", size = 2.5) +
  xlab('temp') +
  ylab('length')
p

New attempt below:
p = ggline(df,x="temp",y="var1", size = 2.5) +
  geom_point(df, aes(x = temp, y = var2), color = "blue") +
  xlab('temp') +
  ylab('length')
p


text:
Q: Trying to add a password visibility toggle to the password input fields on magento 2 checkout pages I need to add a password toggle visibility to the password input fields in magento 2 checkout pages and I can't find a way to work with knockout js.
I am using only javscript to add a span with a click event that changes the input field type from password to text, and it works on all inputs except the ones from the checkout pages.
I want to avoid making any changes to xml or template files, I was looking for a solution to do this only with javascript.
This is the code I have in my module:
require(['jquery'], function($) {$(function() {

    var passwordInput = document.querySelectorAll('input[type="password"]');

    passwordInput.forEach(function(selectedInput) {
       var passwordToggle = document.createElement('span');
       passwordToggle.setAttribute('class', 'show-password');

        selectedInput.parentNode.appendChild(passwordToggle);

        passwordToggle.addEventListener('click', function() {
            if (selectedInput.type === "password") {
                selectedInput.type = "text";
                this.classList.add('visible');
            } else {
                selectedInput.type = "password";
                this.classList.remove('visible');
            }
        });
    });

});});


text:
Q: Convert string representation of an array into an array - C# Given this string:
"['some value','another value','value three']"
What is the most efficient way of converting it to an array? Or any enumerable-type, for that matter?
EDIT: The array would contain the inner string values:
arr[0] = some value
arr[1] = another value
arr[2] = value three

A: It's json-array, use http://james.newtonking.com/json for this
 public static T JsonDeserialize<T> (string jsonString)
 {
     DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
     MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
     T obj = (T)ser.ReadObject(ms);
     return obj;
 }

A: Well, if you can assume that each item will not have a comma, then it could be as straight forward as:
const string value = "['some value','another value','value three']";

var array =
   value
   .Substring(1, value.Length - 2)
   .Split(',')
   .Select(item => item.Substring(1, item.Length - 2))
   .ToArray();

If you can't assume there are no commas, but can assume there are no sequences of apostrophe-comma-apostrophe, then you could do this:
const string value = "['some value','another value','value three']";

var array =
   value
   .Substring(1, value.Length - 2)
   .Split(new[] { "','" }, StringSplitOptions.RemoveEmptyEntries)
   .ToArray();

array[0] = array[0].Substring(1, array[0].Length - 1);
int x = array.Length - 1;
array[x] = array[x].Substring(0, array[x].Length - 1);

Otherwise your options would be:

*

*'manually' loop through the data, keeping track of what's inside of each pair of apostrophes

*using a regex, though I'm not sure how well that would work

*as Igor has said, use a JSON deserializer, if this is indeed something that could be deserialized that way

A: This is just a possible way:
        var str = "['some value','another value','value three']";

        // eliminate '[' and ']'
        str = str.Substring(1, str.Length - 2);

        // remove '
        str = str.Replace("'", string.Empty);

        // split it in a array
        var items = str.Split(',');

For further information about splitting strings, you can use die MSDN
Hope it helps.

A: string s = "['some value','another value','value three']";
s=s.Replace("[", "").Replace("'","").Replace ("]","") ;
List<string> names = s.Split(',').ToList<string>();


text:
Q: How to disable Git auto-detecting email address? On my desktop, if I don't explicitly set the user and email for a repository, git will throw an error saying it was unable to auto-detect my email address and will stop my commit. Given I work on a number of different repositories and want different author/email settings for each, I quite like this functionality.
I know this happens because my user/email is not configured. I am not asking how to resolve this error. Instead, I would like to know if it is possible, and if so how, to configure git to never auto-detect my email address?
On my laptop it does auto-detect. I then configure my user/email but then have to amend my commit. I would like it to reject my commit if I have not configured my user/email.

A: Set user.useConfigOnly to true. (Assuming git >=2.8)
This will make git error out if no name or email are configured.
git config --global user.useConfigOnly true


text:
Q: Remove attribute from object I got a list that return from below db call.
List<employee> list = empolyeeRepository.findByEmployeeId(id);

List contains employee pojo class object. I want to remove one attribute let's say "employee bank account no" when returning from rest call.
@RequestMapping(value = "/employeeInformation/{id}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
public List<Employee> getEmployeeInformation(@PathVariable("id") String id) throws Exception {
    return empolyeeRepository.findByEmployeeId(id);
}

Is there any annotation or good practice to do that?

A: As it mentioned in comments above, you cant remove fields of compiled class at runtime. Assuming you have to exclude some field from generated json, there I see two options:

*

*Create a class with fields you want to be present in resulting json, copy required values from original object to a new created. This approach is called view model and allows you to decorate some object's data, hiding sensitive data from being exposed.

*Depending on implementation of your  serializer there may be annotations to exclude fields. @JsonIgnore may be placed on getter method, if you are using Jackson (default in spring boot). Second aproach requires significant less code, but the first one is more flexible.

A: Try @JsonIgnore to ignore properties from serialization and de-serialization.
Here is the link to the docs


text:
Q: LVM: How to re-use unwanted logical volume space on an existing volume We have this old CentOS4 box and I am trying to increase the space.
I want the full 8GB to show up in a "df -h" but it shows only the first Volume of ~4GB. How can I add the 2nd volume to the first? Can I just edit fstab and mount the Group?? After creating my notes below it looks like the 2nd volume is swap space. Can I just remove the swap space and make it disk space on the first volume? If so how??
# df -h
Filesystem            Size  Used Avail Use% Mounted on
/dev/mapper/VolGroup00-LogVol00 3.9G  3.1G  662M  83% /
/dev/xvda1                       99M   13M   81M  14% /boot

# vgdisplay -s
"VolGroup00" 7.88 GB   [7.88 GB   used / 0    free]

# lvdisplay | grep Name
LV Name                /dev/VolGroup00/LogVol00
VG Name                VolGroup00
LV Name                /dev/VolGroup00/LogVol01
VG Name                VolGroup00

# sfdisk -s
/dev/xvda:   8388608

# less /etc/fstab
/dev/VolGroup00/LogVol00 /                       ext3    defaults        1 1
LABEL=/boot             /boot                   ext3    defaults        1 2
/dev/VolGroup00/LogVol01 swap                    swap    defaults        0 0

A: You are making a confusion between the http://en.wikipedia.org/wiki/File_system on top of the LVMs and the Logical Volumes Manager.
Logical volumes are block devices and you can put a filesystem on top of them. If you want to merge 2 filesystem (or, in your case, discard one and merge the space onto the other), you would need to:

*

*Backup the data on each of the filesystems (also safe to backup the block device, whatever it would be, like a logical volume, but ONLY if it is not mounted)

*Remove one of the logical volumes

*Extend the remaining logical volume to also include the space of the deleted one

*Extend the filesystem that sits on top of the remaining logical volume (ext4 and most of the modern filesystems support online growing but they will most likely do a filesystem check at the next mount). If your filesystem is offline, you will be forced to run a filesystem check before running the resize command.

man lvremove
man lvextend
man fsck
man resize2fs

A: The question is, erm, a little confusing, but if I understand what you want correctly, you're trying to reclaim the drive space taken up by swap and use it for your LV that holds your root file system.  Easy enough, if you have the right underlying filesystem.  Ext3 can dynamically expand the file system while hot, which means you're in luck because your root filesystem is ext3.  As root (please excuse any naming issuess with the LV tools, it's been months since I've had to do this and I know there are cases where you specify the path rather than simply the name):
swap off
lvremove LogVol01
lvresize --size +3.5G LogVol00
resize2fs /

The swap off portion does what it says on the tin, which should remove the swap space from active use.  The lvremove will blow the swap partition way completely and return it as free space to use in the volume group.  The lvresize will then push the partition out, in the process claiming the newly-formed space.  The resize2fs then expands the filesystem mountpoint to use all of the partition space it currently resides on.
Don't forget to remove your swap instance from /etc/fstab.

A: I would strongly disregard of running any Linux without SWAP! It may be small, say, as small as 1/4 of your RAM, but without it your system will most definitely run into SERIOUS problems. It's DESIGNED to have and use a swap space. If you have multiple SWAP volumes and want to downsize swap to use just one, not shown in your outputs, then that should be fine, but I assume you haven't intentionally removed that from your terminal dumps?


text:
Q: SQLiteConstraintException: error code 19: constraint failed Android I am trying to insert lat and long coordinates into a SQLite table and I am getting SQLiteConstraintException: error code 19: constraint failed.
I have the code surrounded by try/catch and no exception is thrown. I get the constraint error in my logcat.
I have attached the DB class and the call from my main activity. Any help or guidance would be very much appreciated!
Here are the top few lines from my logcat:
08-25 14:39:06.934: E/SQLiteDatabase(681): Error inserting lat=59310767 longi=-8613281
08-25 14:39:06.934: E/SQLiteDatabase(681): android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
08-25 14:39:06.934: E/SQLiteDatabase(681):  at android.database.sqlite.SQLiteStatement.native_executeInsert(Native Method)
08-25 14:39:06.934: E/SQLiteDatabase(681):  at android.database.sqlite.SQLiteStatement.executeInsert(SQLiteStatement.java:113)
08-25 14:39:06.934: E/SQLiteDatabase(681):  at android.database.sqlite.SQLiteDatabase.insertWithOnConflict(SQLiteDatabase.java:1745)
08-25 14:39:06.934: E/SQLiteDatabase(681):  at android.database.sqlite.SQLiteDatabase.insert(SQLiteDatabase.java:1618)

Here is the code from my DbHelper:
public void onCreate(SQLiteDatabase db)
{
    // TODO Auto-generated method stub
    db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
            KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            KEY_LAT + " REAL NOT NULL, " +
            KEY_LONGI + " REAL NOT NULL)"

            // KEY_NAME + " TEXT NULL, " +
            // KEY_INFO + " TEXT NULL);"
    );
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // TODO Auto-generated method stub
    db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
    onCreate(db);
}

Here is my DatabaseManager
public DatabaseManager(Context c) {
    ourContext = c;
}

public DatabaseManager open() throws SQLException {
    ourHelper = new DbHelper(ourContext);
    ourDB = ourHelper.getWritableDatabase(); //example show writeable
    return this;
}

public void close() {
    ourHelper.close();
}

public long createPin(long latitude, long longitude) {
    ContentValues cv = new ContentValues();
    cv.put(KEY_LAT, latitude);
    cv.put(KEY_LONGI, longitude);

    return ourDB.insert(DATABASE_TABLE, null, cv);
}

This is the call from my MainActivity:
try{
    long longitude= touchedPoint.getLongitudeE6();
    long latitude= touchedPoint.getLatitudeE6();

    //Add Pin to the Database
    DatabaseManager db = new DatabaseManager(MainActivity.this);
    db.open();
    db.createPin(latitude,longitude);
    db.close();
}

A: remove the keyword AUTOINCREMENT.
It is not necessaty for sqlite.
if you try to insert a null value into a primary integer key the field is automatically converted into an integer which is one greater than the largest value of that column.
Furthermore you have to clear your appdata on your emulator. After that you can be sure that the database is empty.

A: Replace: AUTO_INCREMENT instead of AUTOINCREMENT
                  ^


text:
Q: Why does Radiant incorrectly show Uniform distributions? I ran a Uniform distribution with variable X1 that spans the values 0 to 1. I ran the simulation 100,000 times then graphed the distribution with 50 bins.
Uniform Distribution

I noticed that Bin 1 and Bin 50 show only half the counts of all the other bins (around 1000 instead of 2000). I thought this may have been because of how Radiant splits Bins so I graphed the distribution with other numbers of bins but the first and last bin always have half the counts as the other bins.
Why is the uniform distribution showing up like that? Shouldn't all bins be around the same amount?


text:
Q: boost.python string management How does boost.python handle std::string member variables?
Specifically, if I have a class and its boost.python wrapper
class A {
public:
    std::string name;
};
class_<A>("AWrapper")
.def_readwrite("name", &A::name);

how is the correspondence between std::string object and PyObject it(string) representing is handled:
is boost::python::object(i.e. PyObject) created which stores pointer to the string, thus this object servers as a proxy?
Thus, each time I want to retrieve string member's value, PyString object is created?
Can interning mechanism be applied to such string objects?

A: Short answer: your suspicions and insight about the behaviour is mostly correct, boost-python will interpret your configuration to produce a simple and inefficient behaviour, however it provides support mechanisms to override and extend this. This may be a lot of work.
Long answer:

is boost::python::object(i.e. PyObject) created which stores pointer to the string, thus this object servers as a proxy?

No.
Python-strings are immutable and by default (with your configuration) boost-python will convert the std::string into a new python string (str). So there is no proxying going on.

Thus, each time I want to retrieve string member's value, PyString object is created?

Yes. The following assertion will fail, where I attempt to verify that the python references to the strings have the same python object id.
input = 'some value'
sut = AWrapper()
sut.name = input
assert id(sut.name) == id(input)

Can interning mechanism be applied to such string objects?

For example, if you can enable caching of the created python string-object for a given c++ string, to then return a previously created python string-object when available? The answer is also yes, it is possible. The boost-python concepts are call policies or custom converters. (Both are not part of the tutorial for boost-python.)
You would either extend every def_readwrite call with an appropriate call policy, or overwrite the general built-in converter for std::string to/from PyString, to introduce this theoretical cache.
Keep in mind, python strings are immutable and std::string is mutable. So you will have issues when the member is changed from the C++ side. Additionally, such hooks will also cost performance at runtime when the code handles every single get and set operation.


text:
Q: PHP Function Dependent on presence of MySQL data entry I code a weekly trivia program for one of my clients through facebook.
I have a bit of code commented out where we display the winner when we need to. Currently I just remove the comment brackets and update when it's time to display. I'm trying to make this so someone non-savvy can handle updates so I've moved my code into an include:
winner-display.php
I am trying to write a function so that if the winner is set in MySQL, it includes the file in-line, and if the winner field is empty in the database, it does not.
Here is what I have so far, any ideas?
<?php
$target="3";
$myDataID = mysql_query("SELECT topic_desc from ref_links WHERE ref_categories_id = '$target' AND topic_name = '$property'", $connectID);
while ($row = mysql_fetch_row($myDataID)) {
    $displayvalue = $row ['topic_desc'];
}
if ( $displayvalue != 'null') {
    include('../includes/winner-display.php');
} else {
}
?>

Ok, thanks for helping guys, got it to work as:
<?php
$target="3";
$myDataID = mysql_query("SELECT topic_desc from ref_links WHERE ref_categories_id = '$target' AND topic_name = '$property'", $connectID);
    while ($row = mysql_fetch_row($myDataID)) {
    foreach ($row as $field) {
        if ($field != null) {
            include('../includes/winner-display.php');
        }
    }
}

?>

A: You can definitely put an include within an if.  That solution that you posted should work as you would like it to, although I personally would have used a function instead of a completely separate file to include (although that is personal preference).
All you have to do to make it work is remove the quotes around 'null'.
<?php
$target="3";
$myDataID = mysql_query("SELECT topic_desc from ref_links WHERE ref_categories_id = $target' AND topic_name = '$property'", $connectID);
while ($row = mysql_fetch_row($myDataID)) {
    $displayvalue = $row ['topic_desc'];
}
if ( $displayvalue != null) {
    include('../includes/winner-display.php');
}
?>

Keep in mind that if your query returns more than one row, only the last row will be retained.  I don't know if that is the functionality you want (in which case, there are some changes you could make, just ask me to edit my answer), but I didn't change that.


text:
Q: Filtering ROOT path with Restlet and GAE I have this code that I need to be able to trigger the MyFilter when ROOT_URI is accessed:
private static final String ROOT_URI = "/";
private static final String ROOT_REST_URI = "/rest/";

@Override
public Restlet createInboundRoot() {
    Guice.createInjector(new GuiceConfigModule(this.getContext()),
            new SelfInjectingServerResourceModule());

    Router router = new Router(getContext());

    router.attach(ROOT_URI + "{id}", new GaeRedirector(getContext(), "{id}"));
    router.attach(ROOT_REST_URI, GaeRootServerResource.class);

    MyFilter mFilter = new MyFilter(getContext());
    MyFilter.setNext(router);

    return mFilter;
}

The MyFilter is only triggered when ROOT_REST_URI is accessed. Restlet team already advised through mail group that I need to put a routing into the ROOT_URI first.
The question is,

*

*the ROOT_URI is not in the routing because in the web.xml, a welcome-file setting is there pointing to index.html. So when http://localhost:8080/ is accessed it returns the index.html page.

I have also tried adding (as a routing to ROOT_URI to make MyFilter work on ROOT_URI):
Directory directory = new Directory(getContext(), "war:///doc");
router.attach(ROOT_URI, directory);

Yet, this Directory routing would not work with GAE. It seems it does not trigger at all. accessing the http://localhost:8080/ with this Directory code in place, still the index.html is shown and no MyFilter is triggered.
Now if I remove the <welcome-file> in web.xml. The MyFilter gets triggered but the index.html cannot be shown now. Unless explicitly through adding /index.html to the request.
What solution there may be for this scenario?

A: I would try to set the default index name for the directory as follow:
Directory directory = new Directory(getContext(), "war:///doc");
directory.setIndexName("index.html");


text:
Q: Selenium PhantomJS Java - Refused to evaluate a string because 'unsafe-eval' is not an allowed I'm playing with Selenium and PhantomJS. I'm trying to draw all the elements from a web page. When I retrieve some web page and then I try to get the position of any web element I get this error when I select the web element on my code:
org.openqa.selenium.WebDriverException: {"errorMessage":"Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: \"script-src assets-cdn.github.com\".\n","request":{"headers":{"Accept-Encoding":"gzip,deflate","Cache-Control":"no-cache","Connection":"Keep-Alive","Host":"localhost:26310","User-Agent":"Apache-HttpClient/4.4.1 (Java/1.8.0_45)"},"httpVersion":"1.1","method":"GET","url":"/location","urlParsed":{"anchor":"","query":"","file":"location","directory":"/","path":"/location","relative":"/location","port":"","host":"","password":"","user":"","userInfo":"","authority":"","protocol":"","source":"/location","queryKey":{},"chunks":["location"]},"urlOriginal":"/session/77ee7e10-1077-11e6-9f8f-1f750417371e/element/%3Awdc%3A1462201609875/location"}}

My code is the following. I'm using Jsoup to get the elements because with selenium I often got the same error as previously mentioned:
    WebDriver driver = new PhantomJSDriver();
    driver.manage().window().setSize(new Dimension(1366, 768));
    driver.get(URL);
    Document doc = Jsoup.parse(driver.getPageSource());
    Elements e1 = doc.body().getAllElements();
    ArrayList<String> tags = new ArrayList<>();
    for (Element e : e1) {
        if (tags.indexOf(e.tagName()) == -1) {
            tags.add(e.tagName());
            List<WebElement> query = null;
            if (driver.findElements(By.tagName(e.tagName())).size() < 1) {
                continue;
            }
            try {
                query = driver.findElements(By.tagName(e.tagName()));
            } catch (Exception ex) {
                continue;
            }
            for (WebElement temp1 : query) {
                try {
                    Point po = temp1.getLocation();
                    Dimension d = temp1.getSize();
                    if (d.width <= 0 || d.height <= 0 || po.x < 0 || po.y < 0) {
                        continue;
                    }
                    graph.draw(new Rectangle(po.x, po.y, d.width, d.height));
                } catch (WebDriverException ex) {
                    System.out.println("Error!");
                    ex.printStackTrace();
                }
            }
        }
    }

Why I can't get the position from an element?

I'm using selenium 2.46, PhantomJS 2.0.0 and, for example, this page have problems https://github.com/ariya/phantomjs/issues/13114

A: Have you tried using chromedriver or geckodriver? PhantomJS hasn't been under active development in a while so you might run into some issues with it.
http://chromedriver.chromium.org/
https://github.com/mozilla/geckodriver/releases


text:
Q: Modal popup whit Symfony In fact my problem is that I want to make a "modal" popup that will look for another twig file.
I mexplique, I have my page "profile", and in my profile page I have a button that directs me to another page "edit", here is an example:
profile:
enter image description here
edit:
enter image description here
but here after several tries I can not do it. I already created a similar project with "Angular" or I could add the template I wanted but I block it.
here is how I try to do:
profile:
>

    Editer mon profile

edit:

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Editer mon Profile

                    {{ form_start(form, { 'action': path('fos_user_profile_edit'), 'attr': { 'class': 'fos_user_profile_edit' } }) }}
                    {{ form_widget(form) }}

                        <input class="btn btn-success" type="submit" value="{{ 'profile.edit.submit'|trans }}" />

                    {{ form_end(form) }}

can you help me please?
BOOtstrao.css and JS:

<link href="{{ asset('css/bootstrap.css') }}" rel="stylesheet">

A:
try to replace {{ path('fos_user_profile_edit') }} to #edit

A: So you want to have a profile page and a profile edit form in a modal box on the same page. Please lay back, take a cup of coffee and think. A modal is just a div on a web-page together with all the other html. The only thing is that the modal will be hidden by a css rule, something like display: none; and with some javascript the content can be shown. Now one page means one route and one controller-action that on his turn calls one twig template. (that this twig template can include an other (partial) template is something else, the result will still be one html page at the end). In your show-action you will need to generate the edit form too because the form must be placed into the hidden div. So instead of having two traditional actions show and edit you will need one action for both. Cheers


text:
Q: AI and Design of an El-fish like simulator environment? first post here on stack overflow, hoping to get some advice on how to construct a simulation program akin to the 1993 maxis simulator known as El-Fish wiki here , Also, game info here .
Are there known "Simulation system" algorithm groups that can function and create real life interaction etc... e.g. the visualization known as 'flocking' ? Or, is there an open-source code base to study off of already in construction?
Programming wise, would this also be able to be easily done in a purely functional language? if done in an OOP way, i was thinking of prototyping it in python.
Anyways thanks for any direction in pointing me towards a good starting place. I hope to build a graphical view of an idea/data world. It will be hopefully controlled by underlying simulation AI(heuristics maybe?)

A: In terms of simulation systems, I recommend you search for "agent-based modeling" software. There are a lot of free toolkits available. The two I like the most are NetLogo and Repast.
Also, it looks like you are implementing a "genetic algorithm". There are many good books and pages on that topic.
Python is good, but so are many other languages.
Most of your time will be spent doing the graphics: animating the fish so they look realistic. Unless you can find a free fish-animation-library.

A: I recommend you try my own GarlicSim framework. It's written in Python and you'll be writing your specific simulation in Python.
It can definitely handle the kind of simulation you want. There are tutorials available which will teach you the basics of GarlicSim in 30 minutes. I'll be happy to help you build your simulation package, just say hello on the mailing list and I'll guide you from there.

A: I'm not sure about "real life", but there is a flocking algorithm called boids that might be a good example to start from.  There are a couple python versions of it as well.  There's one that is an example in the owyl project on google code.


text:
Q: For which values of c does the system have a solution? I was doing my homework and stumbled upon this question where I have a system of 3 equations with 5 unknowns/variables. I got stuck trying to make it into an echelon form of this matrix.
The problem is stated as follows:

Find which values of c does the system have a solution? For each c, find all solutions as linear combinations of certain vectors.

In the image below I tried to solve it but got stuck and I'm not sure how to continue this equation..

A: Set $x_5 = c $ and $x_6 = c^2 $, then the system becomes
$\begin{bmatrix} 2&&1&&5&&4&&0&&-1 \\ 1 && -1&& 1 &&-1&&-4&&0 \\ 1 && 0 && 2 && 1 && -1 && 0 \end{bmatrix} \begin{bmatrix} x_1 \\ x_2 \\ x_3 \\ x_4 \\ x_5 \\ x_6 \end{bmatrix} = \begin{bmatrix} 2 \\ 5 \\ 3 \end{bmatrix} $
Solving using Gauss-Jordan elimination, the solutions are
$\begin{bmatrix} x_1 \\ x_2 \\ x_3 \\ x_4 \\ x_5 \\ x_6 \end{bmatrix} = \begin{bmatrix} 5 \\ -8\\ 0 \\ 0 \\ 2 \\ 0 \end{bmatrix} + t_1 \begin{bmatrix} -2 \\ -1 \\ 1 \\ 0 \\ 0 \\ 0 \end{bmatrix} + t_2 \begin{bmatrix} -1 \\ - 2 \\ 0 \\ 1 \\ 0 \\ 0 \end{bmatrix} + t_3 \begin{bmatrix} -1 \\ 3 \\ 0 \\ 0 \\ -1 \\ 1 \end{bmatrix} $
From which it follows that
$x_5 = c = 2 - t_3 $ and $ x_6 = c^2 = t_3 $
Hence, we must have $2 - c = c^2 $, i.e. $c^2 + c - 2 = 0$ which can be factored as $ (c + 2)(c - 1) = 0 $.  Therefore, the two values of $c$ for which there is a solution are $c = -2 $ and $c = 1$.
For $c = -2$, we get $t_3 = 4 $  and for $c = 1$ we get $t_3 = 1 $
Therefore, there are two corresponding sets of solutions:
Case I: for $c = -2$ we get,
$\begin{bmatrix} x_1 \\ x_2 \\ x_3 \\ x_4  \end{bmatrix} = \begin{bmatrix} 1 \\ 4 \\ 0 \\ 0  \end{bmatrix} + t_1 \begin{bmatrix} -2 \\ -1 \\ 1 \\ 0  \end{bmatrix} + t_2 \begin{bmatrix} -1 \\ - 2 \\ 0 \\ 1 \end{bmatrix}  $
Case II:  for $c = 1$, we get,
$\begin{bmatrix} x_1 \\ x_2 \\ x_3 \\ x_4  \end{bmatrix} = \begin{bmatrix} 4 \\ -5 \\ 0 \\ 0  \end{bmatrix} + t_1 \begin{bmatrix} -2 \\ -1 \\ 1 \\ 0  \end{bmatrix} + t_2 \begin{bmatrix} -1 \\ - 2 \\ 0 \\ 1 \end{bmatrix}  $


text:
Q: How to install a python library manually I built quickfix engine (http://www.quickfixengine.org/) for one of my tasks and also built in python support for it.
Unfortunately this is a multi user env and I dont have access to the python installation path. Thus the make install command tries to copy over the files and fails. I managed to comment out the two lines where it tries to do that and the make install completed. Since I cannot put the files there, where can I put the .so file created?
And how do I let python know that it is there? I looked at python.org documentation but it only describes the process for setup.py installations.
Also I tried putting the path for the .so in  sys.path, that didnt work. And is there any documents about the anatomy of a python package? Thanks.

A: You need to install it in a directory in your home folder, and somehow manipulate the PYTHONPATH so that directory is included.
The best and easiest is to use virtualenv. But that requires installation, causing a catch 22. :) But check if virtualenv is installed. If it is installed you can do this:
$ cd /tmp
$ virtualenv foo
$ cd foo
$ ./bin/python

Then you can just run the installation as usual, with /tmp/foo/python setup.py install.
(Obviously you need to make the virtual environment in your a folder in your home directory, not in /tmp/foo. ;) )
If there is no virtualenv, you can install your own local Python. But that may not be allowed either. Then you can install the package in a local directory for packages:
$ wget http://pypi.python.org/packages/source/s/six/six-1.0b1.tar.gz#md5=cbfcc64af1f27162a6a6b5510e262c9d
$ tar xvf six-1.0b1.tar.gz
$ cd six-1.0b1/
$ pythonX.X setup.py   install --install-dir=/tmp/frotz

Now you need to add /tmp/frotz/pythonX.X/site-packages to your PYTHONPATH, and you should be up and running!

A: Here is the official FAQ on installing Python Modules: http://docs.python.org/install/index.html
There are some tips which might help you.

A: I'm going to assume compiling the QuickFix package does not produce a setup.py file, but rather only compiles the Python bindings and relies on make install to put them in the appropriate place.
In this case, a quick and dirty fix is to compile the QuickFix source, locate the Python extension modules (you indicated on your system these end with a .so extension), and add that directory to your PYTHONPATH environmental variable e.g., add
export PYTHONPATH=~/path/to/python/extensions:PYTHONPATH

or similar line in your shell configuration file.
A more robust solution would include making sure to compile with ./configure --prefix=$HOME/.local. Assuming QuickFix knows to put the Python files in the appropriate site-packages, when you do make install, it should install the files to ~/.local/lib/pythonX.Y/site-packages, which, for Python 2.6+, should already be on your Python path as the per-user site-packages directory.
If, on the other hand, it did provide a setup.py file, simply run
python setup.py install --user

for Python 2.6+.


text:
Q: PL-SQL realizar consulta mediante filtros null o no hay alguna forma de yo concatenarle a un select un query segun una condicion? por ejemplo en tengo un procedure en el que voy a recibir N parametros de entrada, el query lo tengo listo pero como son filtros no todos los parametros vendran con un valor (se reciben un codigo, fecha desde y fecha hasta), el problema es que en el select que tengo para que me pueda traer la data debo colocarle los valores a todos los parametros, mi pregunta es yo puedo concatenarle mediante un IF si por ejemplo codigo viene lleno le anexo a ese select ese valor y ejecuto?, para que tenga una idea, en java mediante stringQueryBuilder  y la condicion IF, yo puedo agregarle al query mediante .append la condicion de 'and fecha_desde = ?', existe alguna forma en PL o tienen alguna sugerencia?
aca el query
SELECT ORDER_SCHEDULE_NO , S.SUPPLIER, S.SUP_NAME , TO_CHAR(ORDER_DATE,'DD/MM/YYYY HH24:MI:SS'), TO_CHAR(ORDER_CREATE_DATE,'DD/MM/YYYY HH24:MI:SS')
FROM ORDER_SCHEDULE OS, SUPS S WHERE S.SUPPLIER = :SUPPLIER AND TRUNC(order_date) >= TO_DATE(:FECHADESDE,'DD/MM/YYYY hh24:mi:ss')
AND TRUNC(order_date) <= TO_DATE(:FECHAHASTA,'DD/MM/YYYY hh24:mi:ss') AND S.SUPPLIER = OS.SUPPLIER ORDER BY ORDER_DATE

A: Si, puedes.
Para ello puedes usar los SYS_REFCURSOR que son un tipo especial de cursor que puedes ejecutar a partir de un VARCHAR2 (una cadena de caracteres vamos). El VARCHAR2 puedes confeccionarlo a tu gusto usando condicionales IF, tal y como indicas.
Un ejemplo práctico:
Creamos un procedure y declaramos nuestras variables de cursor y varchar2:
PRUEBA_CURSOR SYS_REFCURSOR;
SENTENCIA VARCHAR2(10000);

Después vamos confeccionando la sentencia a nuestro gusto:
SENTENCIA:= 'SELECT ejemplo FROM ejemploTabla WHERE a = 1';

--Si se cumple la condición siguiente, agregamos un AND al where
IF(condicionEjemplo) THEN
    SENTENCIA := SENTENCIA || 'AND b = 2';
END;

Por último, abrimos el cursor, el cual ejecutará la sentencia:
OPEN PRUEBA_CURSOR FOR SENTENCIA;

Cabe decir que puedes devolver este cursor como parametro OUT en el procedure, o incluso puedes ejecutar un loop por cada registro devuelto por la Select.


text:
Q: Objects with vector not properly setting info in the vector (c++) Heyo! I'm fairly new to C++ but have some background in coding, so a simpler explanation would be fantastic. I have been working on a fairly complicated program and an issue appeared. I have an object called "Tile" being made in a vector.
for (int i = 0; i <= ySize; i++) {
    for (int i2 = 0; i2 <= xSize; i2++) {
        tiles.push_back(make_unique <Tile>());
        tiles[i*xSize + i2]->set_height(fn.GetNoise(i2, i));
        tiles[i*xSize + i2]->set_xPos(i2);
        tiles[i*xSize + i2]->set_yPos(i);
        tiles[i*xSize + i2]->update_tile();
    }
    cout << endl;
}

Ideally the tiles are generated in a grid manner. Within the tile objects is a vector called "goods".
vector unique_ptr<Good*> goods;

These goods are added through the double for loop here:
for (int i = 0; i <= ySize; i++) {
    for (int i2 = 0; i2 <= xSize; i2++) {
        if (tiles[i*xSize + i2]->get_rainfall() >= 0.1 && tiles[i*xSize + i2]->get_height() >= -0.2 && tiles[i*xSize + i2]->get_height() <= 0.55 && fn.GetNoise(i2, i) < 0) {
            tiles[i*xSize + i2]->add_available_good(1001, (fn.GetNoise(i, i2)*500+214));
            tiles[i*xSize + i2]->update_tile();
        }
    }
}

This vector will store child classes of class Good through here:
void Tile::add_available_good(short unsigned int g, short int a) {
//Adds good based on GoodID
switch (g) {
case 1001:
    goods.emplace_back(new Tree(a));
    break;
case 1002:

    break;
default:

    break;
}

}
The problem that has appeared is that whenever I call tiles
[i*xSize + i2]->add_available_good(num, num);

Something goes funny. The size of vector Goods on any given tile becomes the number of goods added to all of the tiles. In other words it appears the goods vector is shared between all of the tile objects. How do I fix this?
I am terrible at explaining things but I tried my best. Thank you in advance!
Tile class definition:
#include <iostream>
#include <windows.h>
#include <string>
#include <vector>
#include <locale>
#include <random>
#include <memory>

using namespace std;

//Misc inclusions
#include "Building.h"
#include "Good.h"

class Tile
{
public:
Tile();
void print_tile();
void set_tile_symbol(char);
char get_tile_symbol();
void set_tile_color(float);
float get_tile_color();
void add_building(short unsigned int);
void set_height(double);
double get_height();
void update_tile();
void add_available_good(short unsigned int, short int);
void set_rainfall(double);
double get_rainfall();
void set_xPos(int);
void set_yPos(int);
short unsigned int get_good(short unsigned int);
short unsigned int get_good_weight(short unsigned int);
void print_good();
~Tile();
private:

char symbol;
int xpos;
int ypos;
float color;
short unsigned int usableSpace = 36;
double height = 0;
int pop = 0;
bool hasPop = 0;
double rainfall = 0;
};

Good class definition:
class Good
{
public:
Good();
void set_weight(double);
void change_weight(double);
double get_weight();
void set_value(double);
double get_value();
void change_value(double);
short unsigned int get_symbolShowsAt();
char get_symbol();
short unsigned int get_goodID();
~Good();
protected:
double weight;
short unsigned int reqFunction[5];
short unsigned int reqGoodID[5];
short unsigned int goodWeight[5];
double value = 1;
short unsigned int goodID = 1000;
short unsigned int functionID = 4000;
bool hasSymbol = 0;
short unsigned int symbolShowsAt = 100;
char symbol = 0;
int size = 1;
};
struct Tree : public Good { Tree(short unsigned int w); };

A: Set the global vector to be a member.


text:
Q: Why is my bloodstain sometimes short on runes? I haven't been able to discern a pattern, but sometimes when I retrieve my bloodstain after dying, it holds roughly 20% fewer runes than I dropped when I died. I've seen threads elsewhere on the internet that say nearby enemies will pick them up - and I have come across mobs (both hostile enemies and non-hostile creatures) with glowing gold eyes that drop far more runes than their non-glowing counterparts. However, there doesn't seem to be any relationship between these mobs and my mysteriously light bloodstains: I've come across them seemingly randomly in the wild (including two enemies in a tomb I'd never visited before), and I've thoroughly examined the surrounding environments when I've noticed my bloodstain is smaller than expected and come up with nothing - so if there is a relationship between the two, it's not an obvious (or geographic) one.

A: I was noticing this too, particularly in Stormveil Castle when I was fighting dying to Godrick. Each time I collected the lost runes, I was noticing a decrease of what seemed to be about a third of what I initially had. It turns out this loss is due to an NPC you meet at the very beginning, when you first ventured into Stormveil Castle, when you met Gatekeeper Gostoc.
Gatekeeper Gostoc is the NPC you meet just next to the main gate to Stormveil Castle. He'll explain to you that you shouldn't take the main gate as it's too dangerous, and you should instead take the side passage next to him. Per the wiki:

Gostoc at first may seem to want to help the player, although in a suspicious manner. This is however just a facade. He will actually steal 30% of your runes every time you die in the castle, even if you enter it through the main gate.

So, while Gostoc lives, each time you die within the castle, you will permanently lose 30% of the souls you originally had. Gostoc's influence also appears to extend to a difficult-to-measure area around the castle, as his influence appears to be a bit larger than just Stormveil Castle. This influence appears to extend to somewhere between Stormhill Shack and Warmaster's Shack.
Once I learned that this was occurring due to him, I went and killed him, and I noticed that since then I wasn't losing 30% of my runes upon death.
You can find Gostoc stalking you in certain locations throughout the castle, which I suppose from a lore perspective explains how he's able to steal your runes each time you die: He's always watching. According to the wiki, he's also the reason you're locked in the room that contains the Rusty Key, as when the cinematic plays you can hear Gostoc cackle as the door slams shut.
Killing him will also give you Gostoc's Bell Bearing.
It is possible that there are other NPCs that will also siphon runes similar to how Gostoc does in other places throughout the game, but I haven't noticed this effect elsewhere yet.


text:
Q: Simple 32 to 64-bit transition? Is there a simple way to compile 32-bit C code into a 64-bit application, with minimal modification? The code was not setup to use fixed type sizes.
I am not interested in taking advantage of 64-bit memory addressing. I just need to compile into a 64-bit binary while maintaining 4 byte longs and pointers.
Something like:
#define long int32_t

But of course that breaks a number of long use cases and doesn't deal with pointers. I thought there might be some standard procedure here.

A: There seem to be two orthogonal notions of "portability":

*

*My code compiles everywhere out of the box. Its general behaviour is the same on all platforms, but details of available features vary depending on the platform's characteristics.

*My code contains a folder for architecture-dependent stuff. I guarantee that MYINT32 is always 32 bit no matter what. I successfully ported the notion of 32 bits to the nine-fingered furry lummoxes of Mars.
In the first approach, we write unsigned int n; and printf("%u", n) and we know that the code always works, but details like the numeric range of unsigned int are up to the platform and not of our concern. (Wchar_t comes in here, too.) This is what I would call the genuinely portable style.
In the second approach, we typedef everything and use types like uint32_t. Formatted output with printf triggers tons of warnings, and we must resort to monsters like PRI32. In this approach we derive a strange sense of power and control from knowing that our integer is always 32 bits wide, but I hesitate to call this "portable" -- it's just stubborn.
The fundamental concept that requires a specific representation is serialization: The document you write on one platform should be readable on all other platforms. Serialization is naturally where we forgo the type system, must worry about endianness and need to decide on a fixed representation (including things like text encoding).
The upshot is this:

*

*Write your main program core in portable style using standard language primitives.

*Write well-defined, clean I/O interfaces for serialization.

If you stick to that, you should never even have to think about whether your platform is 32 or 64 bit, big or little endian, Mac or PC, Windows or Linux. Stick to the standard, and the standard will stick with you.

A: No, this is not, in general, possible.  Consider, for example, malloc().  What is supposed to happen when it returns a pointer value that cannot be represented in 32 bits?  How can that pointer value possibly be passed to your code as a 32 bit value, that will work fine when dereferenced?
This is just one example - there are numerous other similar ones.
Well-written C code isn't inherently "32-bit" or "64-bit" anyway - it should work fine when recompiled as a 64 bit binary with no modifications necessary.

Your actual problem is wanting to load a 32 bit library into a 64 bit application.  One way to do this is to write a 32 bit helper application that loads your 32 bit library, and a 64 bit shim library that is loaded into the 64 bit application.  Your 64 bit shim library communicates with your 32 bit helper using some IPC mechanism, requesting the helper application to perform operations on its behalf, and returning the results.
The specific case - a Matlab MEX file - might be a bit complicated (you'll need two-way function calling, so that the 64 bit shim library can perform calls like mexGetVariable() on behalf of the 32 bit helper), but it should still be doable.

A: The one area that will probably bite you is if any of your 32-bit integers are manipulated bit-wise. If you assume that some status flags are stored in a 32-bit register (for example), or if you are doing bit shifting, then you'll need to focus on those.
Another place to look would be any networking code that assumes the size (and endian) of integers passed on the wire. Once those get moved into 64-bit ints you'll need to make sure that you don't lose sign bits or precision.
Structures that contain integers will no longer be the same size. Any assumptions about size and alignment need to be cleaned out.


text:
Q: Winsock send call is very slow I am making a gameserver (TCP) which might need to handle 3000+ connections.
Currently its having 50 connections and i am already experiencing lags.
I found out that its the winsock send() calls that takes about 100~300ms each to return, which pretty much slow down the whole server as it is a single threaded server.
So far I've thought about two solutions.

*

*Redesign my server to create a thread for each client (Is it really stable to create 3000+ threads for 3000 clients?).

*Find a way to make the send() call to return immediately.

This is my socket init code:
int ret = WSAStartup(MAKEWORD(2,2), &wsaData);
if(ret != 0)
{
    printf("Winsock failed to start.\n");
    system("pause");
    return;
}

server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = htons(52000);

sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == INVALID_SOCKET)
{
    printf("Invalid Socket.\n");
    system("pause");
    return;
}

if(bind(sock, (sockaddr*)&server, sizeof(server)) != 0)
{
    printf("error");
    return;
}

if(listen(sock, 5) != 0)
{
    printf("error");
    return;
}

Accepting code in a separate thread
sockaddr_in from;
int fromlen = sizeof(from);
SOCKET sTmpSocket = accept(ServerSock, (struct sockaddr*)&from, &fromlen);

My send function
void CClient::SendPacket(BYTE* pPacket, DWORD Len)
{
    DWORD ToSendLen = Len;
    while (ToSendLen)
    {
        int iResult = send(this->ClientSocket, (char*)(pPacket + Len - ToSendLen), ToSendLen, 0);

        if (iResult == SOCKET_ERROR)
            return;

        ToSendLen -= iResult;
    }
}

This is my server thread (incomplete, only relevant part)
while (1)
{
    for (int i = 0; i < MAX_CLIENT; i++)
    {
        if (Clients[i].bConnected == false)
            continue;

        timeval timeout;
        timeout.tv_sec = 0;
        timeout.tv_usec = 1;
        fd_set socketset;
        socketset.fd_count = 1;
        socketset.fd_array[0] = Clients[i].ClientSocket;
        if (select(0, &socketset, 0, 0, &timeout))
        {
            int RecvLen = recv(Clients[i].ClientSocket, (char*)pBuffer, 10000, MSG_PEEK);
            if (RecvLen == SOCKET_ERROR)
            {
                Clients[i].bConnected = false;
                iNumClients--;
            }
            else if (RecvLen == 0)
            {
                Clients[i].bConnected = false;
                iNumClients--;
            }
            else if (RecvLen > 0)
            {
                // Packet handling here
                recv(Clients[i].ClientSocket, (char*)pBuffer, dwDataLen, MSG_WAITALL);

                //...
            }
        }
    }

    Sleep(1);
}

Any help would be greatly appreciated.
Thank you.

A: I would go for IOCP (IO completion ports) which can bring the desired performance and which scales well. Take a look at Boost.Asio which is using IOCP under the hood (on windows).
The idea to have 3000 and more threads is very bad and really don't scale (in terms of memory consumption and context switches)!

A: One thing comes to mind immediately, and that is to use non-blocking sockets and check if the sockets is writable with select.
As a side-note, you are using the return value from select wrong. It returns 0 on timeout, a positive number if there are sockets ready in any set, and -1 if there is an error. You do not check for the error. Also, while not needed in the winsock version, the first argument to select should really be the highest socket number plus one.
Another point, you are only using select for one client at a time, add all clients to the set and then do a select:
fd_set readset;
FD_ZERO(&readset);
SOCKET max_socket = 0;

for (int i = 0; i < MAX_CLIENT; i++)
{
    if (Clients[i].bConnected)
    {
        FD_SET(Clients[i].ClientSocket, &readset);
        max_socket = std::max(max_socket, Clients[i].ClientSocket);
    }
}

int res = select(max_socket + 1, &readset, 0, 0, &timeout);
if (res == SOCKET_ERROR)
    std::cout << "Error #" << WSAGetLastError() << '\n';
else if (res > 0)
{
    for (int i = 0; i < MAX_CLIENT; i++)
    {
        if (Clients[i].bConnected && FD_ISSET(Clients[i].ClientSocket, &readset))
        {
            // Read from client
        }
    }
}

A: Another approach to consider is to have multiple worker threads handling a proportion of the active connections and make this configurable.  For example you could create n threads per core and then experiment with n.
This should give you a lot of the benefits of multi-threading without going to the extreme of one thread per client.

A: If you are only sending small packets, set the the TCP_NODELAY option with setsockopt(), to start with.


text:
Q: Asking for an example of a (number) system failed to exist Quite a few analysis books I've looked into start with some number system, claim some (reasonably convincing) axioms on it, assume it to be existed, and build analysis from there. Some explain why the number system exists by constructing it from some more basic number system, but I've probably never came across anything about why some number system does not exist.
Could anyone please explain how some number system does not exist by giving an example?

One of my understandings is that it might be due to the contradiction arisen from the axioms that fails the number system to be existed.
According to page 11 of Pugh's Real Mathematical Analysis (2017):

For what if a system satisfying the axioms failed to exist? Then one would be studying the empty set!

My understanding to this sentence above is as follows: let $U$ be a collection that contains everything that exists that we ever need, and $L$ be the list of axioms that are needed to be satisfied by our number system $X$. Define $X$ as a set such that for each $x \in U$, iff $x$ satisfies everything in $L$ simultaneously, then $x \in X$. Since there is a contradiction in $L$, no element in $U$ would be filled into $X$ through these implications and thus we get $X=\emptyset$. And all the subsequent analyses on $X$ are carried through vacuous implications, that is, by assuming there are elements in the empty set $X$.
May I ask if my understandings are on the right track? (it kinda confuses me...)
And here come some other questions:

*

*Is that possible to have a number system that doesn't exist while the axioms on it are consistent?

*When we say some number system does not exist, does this mean that the entities in the system, speaking of themselves, literally cannot exist? Or does this mean that those entities assumed to be inside the system indeed can exist, but they are just living in somewhere else and the system is empty? (Or are there other interpretations?)

A: Here's an answer to your first question. It's also rather topical right now:
We work over $\mathbb{R}$ throughout.
A Normed Division Algebra is a "number system" which generalizes $\mathbb{C}$ in a similar way that $\mathbb{C}$ generalizes $\mathbb{R}$. More precisely:
A division algebra is a a vector space over $\mathbb{R}$ (so it has addition and subtraction, among other things) which also admits multiplication and division (as long as you don't divide by the $0$ vector).
So you might think of a division algebra as a "number system" (since we can add/subtract/multiply/divide) which contains the reals $\mathbb{R}$ in a nice way. Indeed, $\mathbb{R}$ itself and $\mathbb{C}$ are two good examples of division algebras.
A normed division algebra is a division algebra which also admits a norm $x \mapsto |x|$ which tells you how "big" a number is. Again, $\mathbb{R}$ with the absolute value function, and $\mathbb{C}$ with its standard norm $a + bi \mapsto \sqrt{a^2 + b^2}$ are both examples of this object too.

The drama:
There is a theorem due to Hurwitz which says that if you restrict your attention to "finite dimensional" systems, the only such number systems are

*

*$\mathbb{R}$

*$\mathbb{C}$

*$\mathbb{H}$

*$\mathbb{O}$
So if you are interested in "number systems" which contain $\mathbb{R}$, admit a notion of "size", and "aren't too big", you are FORCED into picking one of these systems.
Rather interestingly, you lose something on each stage.

*

*Passing from $\mathbb{R}$ to $\mathbb{C}$, you lose the ability to order your numbers (is $1 < i$?)

*Passing from $\mathbb{C}$ to $\mathbb{H}$, you lose commutativity (so $ab \neq ba$ in general)

*Passing from $\mathbb{H}$ to $\mathbb{O}$, you lose associativity! That is,
$(ab)c \neq a(bc)$ in general!

What is most interesting, though, is that a few months ago, somebody published an article saying they had found a new algebra, which was like $\mathbb{O}$, but managed to preserve associativity!

That is, they claimed the existence of an $8$-dimensional, associative, normed division algebra.

This is certainly a "number system" of the kind you might be interested in. It is also nonexistent by Hurwitz' Theorem! The paper has since been retracted from the journal, though I believe the author is still fighting the decision, claiming their result is actually true.

So you see, there are cases where mathematicians accidentally study objects which don't exist. There are lots of apocryphal examples as well, but most of them don't fall under the heading of "number systems".

As a rather quick reply to your other questions:

*

*Can a number system fail to exist even when its axioms are consistent?

My instinct says "no". Certainly in the case of a First Order set of axioms, a system exists if and only if the axioms are consistent. This is Godel's Completeness Theorem.
I'm notably less well versed in higher order logics, such as those needed to formalize the completeness of $\mathbb{R}$. In general, completeness/soundness/effectiveness cannot all happen at the same time for higher order logics, and I'm far from an expert in the subtleties of what is and isn't possible. Rather funnily, this is a corollary of Godel's Incompleteness Theorem.
I'm sure if you post another question on this site asking for specifics of completeness of second order logic, you'll find some more specialized logicians than me who are willing to help :)

*

*What does it mean for a system to "not exist"

I think this is better asked to a room of philosophers than a room of mathematicians. For me, it "doesn't exist" if there isn't a model. That is, there is no set equipped with some functions that actually satisfy the axioms.
For instance, there is no noncyclic group of order $2$. Why does this not exist? Because you can look at a set of size $2$, and try all possible group structures, and see for yourself that none of them work. It's the same idea for other objects that "don't exist", we just need cleverer arguments since we can't check by hand that all (possibly infinitely many) options fail.

I hope this helps ^_^


text:
Q: React not recognizing changed state from input boxes on first render Hello fellow devs
I am building a basic client in React to test some functionality of my API, admittedly my Node.js knowledge far surpasses my understanding of react, states and hooks.
The problem:
I have 3 input fields, one for "username", one for "password" and one for "confirmPassword". Each of these inputs values update based of a "subscriber" useState hook. that I have set using a handleChange function with an onChange listener placed in each input.
I then have two buttons which rely on a separate use state hook called logOrReg to change based on if the user wants to login or register. This hook will adjust the function the submit button hits as well as the text in the submit button and the text in the the button used to switch to login or register.
On the first render when I launch the app the logOrReg state appears to be set correctly being submit button function: function postSub login-or-register button text: "Already have an account?" and Submit button text: "register".
When I start typing text into the inputs they update accordingly and so does the subscribers state via the handleChange function placed into each input. I then go to click the submit button, it then hits the postSub function but the the subscribers state does not get passed to the function and so the API receives blank values in its console and the subscriber.username and subscriber.password targets in the postSub function come out blank in a console.log on the client side.
However if I click "already have an account?" the buttons switch (with the text in the inputs staying the same) and then click  "Don't have an account?" the buttons change back to the register state as expected. I then click "register" and the values from the subscriber state set in the inputs suddenly get passed over to the postSub function and the API receives the password and username and registers the new user.
Then if I try to update the values in the input fields again the updated values don't get passed to the postSub function but instead the values from the initial registration get passed to the function and subsequently the api returning a message on my API console stating that the user has already been registered.
When looking at my components and states in the React dev tolls in the google developer console they all appear to be updating correctly, so its super confusing that when I click submit the state of the inputs doesn't get passed to the function. My assumption is I am not understanding how the useState hooks work but if they are displaying correctly in the Dev tools I have no idea how to understand why the values are not being passed to the function.
I really hope this makes sense, its such a weird problem to describe.
The code:
import React, {useState, useEffect} from 'react'
import Pusher from 'pusher-js';
import axios from "axios";
import Table from '@mui/material/Table';
import TableHead from '@mui/material/TableHead';
import TableCell from '@mui/material/TableCell';
import TableRow from '@mui/material/TableRow';

const PUSHER_APP_KEY = "b4173b2b1b29274b8621";
const PUSHER_APP_CLUSTER = "eu";

function Resthome(e) {

    const pusher = new Pusher(PUSHER_APP_KEY, {cluster: PUSHER_APP_CLUSTER})

    // var [activeOrders,     setActiveOrders] = useState([])
    // axios.get("hhttp://localhost:3000/restaurants/getactiveorders")
    // .then(response => {         setActiveOrders(response)     })
    // console.log(activeOrders) This will be called when your component is mounted
    useEffect(() => {

        const channel = pusher.subscribe("rests")
        let mounted = true;
        if (mounted) {
            console.log("mounted")

            channel.bind("inserted", (data) => {
                console.log("inserted")
                console.log("data", JSON.stringify(data))

                alert("you have been subscribed")

            })
        }
        return (() => {
            pusher.unsubscribe("rests")
            mounted = false
        })
    }, []);

    // [] would ensure that useEffect is executed only once

    function LoginOrRegister() {

         const [subscriber,
            setSubscriber] = useState({
                username: "",
                password: "",
                confirmPassword: ""
            })

               const [logOrReg,
            setLogOrReg] = useState({type: "reg", function: postSub, submitButton: "register", switchButton: "already have an account?"})

        function handleChange(event) {

            const newValue = event.target.value;
            const inputName = event.target.name;

            setSubscriber(prevValue => {
                if (inputName === "username") {
                    return {username: newValue, password: prevValue.password, confirmPassword: prevValue.confirmPassword}
                } else if (inputName === "password") {
                    return {username: prevValue.username, password: newValue, confirmPassword: prevValue.confirmPassword}
                } else if (inputName === "confirmPassword") {
                    return {username: prevValue.username, password: prevValue.password, confirmPassword: newValue}
                }
            })

            console.log("set sub username", subscriber.username, "set sub password", subscriber.password)

        }

        function Switch(e) {

            e.preventDefault()

            if (logOrReg.type === "reg") {
                setLogOrReg({type: "log", function: logUser, submitButton: "login", switchButton: "Dont have an account?"})
            } else if (logOrReg.type === "log") {
                setLogOrReg({type: "reg", function: postSub, submitButton: "register", switchButton: "Already have an account?"})
            }

        }

        async function postSub(e) {
            e.preventDefault()

            console.log("password", subscriber.password, "username", subscriber.username)

            try {
                if (subscriber.password === subscriber.confirmPassword) {
                    await axios
                        .post("http://localhost:3000/restaurants/register", {

                        username: subscriber.username,
                        password: subscriber.password

                    })
                        .then(response => {
                            if (response.status === 201) {
                                console.log("request sent successfully")
                            }
                        })

                } else {
                    alert("Passwords dont match")
                }
            } catch (err) {
                console.log(err)
            }
        }

        async function logUser(e) {
            e.preventDefault()

            try {
                if (subscriber.password === subscriber.confirmPassword) {
                    await axios
                        .post("http://localhost:3000/restaurants/login", {

                        username: subscriber.username,
                        password: subscriber.password

                    })
                        .then(response => {
                            if (response.status === 201) {
                                console.log("request sent successfully")
                                console.log(response)
                            }
                        })

                } else {
                    alert("Passwords dont match")
                }
            } catch (err) {
                console.log(err)
            }
        }

        // var [logOrReg,     setlogOrReg] = useState({username: "", password: "",
        // confirmPassword: ""})

        return (

                <form onSubmit={logOrReg.function}>

Signup

                    <input
                        name="username"
                        onChange={handleChange}
                        placeholder="username"
                        value={subscriber.username}
                        label="email"></input>
                    <input
                        name="password"
                        onChange={handleChange}
                        placeholder="password"
                        value={subscriber.password}
                        label="password"></input>
                    <input
                        name="confirmPassword"
                        onChange={handleChange}
                        placeholder="confirmPassword"
                        value={subscriber.confirmPassword}
                        label="password"></input>
                    <button type="submit">

                            {logOrReg.submitButton}

                    </button>
                </form>
                <button name="login-or-register" onClick={Switch}>

{logOrReg.switchButton}

                </button>

        )
    };

    return (

            <LoginOrRegister/>

                <TableHead>
                    <TableRow>
                        <TableCell>ID</TableCell>
                        <TableCell align="right">Total</TableCell>
                        <TableCell align="right">Item names</TableCell>
                        <TableCell align="right">Status</TableCell>
                        <TableCell align="right">Time Placed</TableCell>
                    </TableRow>
                </TableHead>

    )
}

export default Resthome

A: Reason
The problem here is that your function have not a reference to your state as described here at react documentation
Explanation
If you store a function in state the function captures the variable from outer scope (AFAIK copy operation).
When your state changes your function still holds the old copy.
If you want that your function captures the new state you have to recall it (create a new reference to that function in your state).
You could use "useEffect" to re-render your invocation function when your state changes
Possible solution
Example on StackBlitz
But...
And the end you should prefer to extract your function from your state and make the decision in a static function with a conditional/switch-case on your state

A: For anyone who this may help see my  solution below. I also cleaned up the birds nest and moved the LoginOrRegister component to its own file.
import React, {useState} from 'react'
import axios from "axios";

const MODE_REGISTER = "register";
const MODE_LOGIN = "login";

function LoginOrRegister({setCount, count}) {

    // REGISTER FUNCTION
    async function register() {

        console.log("password", formState.password, "username", formState.username)

        if (formState.password === formState.confirmPassword) {
            axios({
                method: "POST",
                data: {
                    username: formState.username,
                    password: formState.password
                },
                withCredentials: true,
                url: "http://localhost:3000/restaurants/register"
            }).then((res) => {console.log(res)

            setCount("allow")
            });

        } else {

            alert("passwords dont match")
        }

    };

    // LOGIN FUNCTION
    async function login() {

        console.log("password", formState.password, "username", formState.username)

        if (formState.password === formState.confirmPassword) {
            axios({
                method: "POST",
                data: {
                    username: formState.username,
                    password: formState.password
                },
                withCredentials: true,
                url: "http://localhost:3000/restaurants/login"
            }).then((res) => {

        console.log(res)
    setCount("allow")
    });

        } else {

            alert("passwords dont match")
        }

    };

    const [formState,
        setFormState] = useState({mode: MODE_REGISTER, username: "", password: "", confirmPassword: "", logState: "false"});

    function handleChange(event) {
        const newValue = event.target.value;
        const inputName = event.target.name;

        setFormState({
            ...formState,
            [inputName]: newValue
        })
    };

    function handleSubmit(event) {
        event.preventDefault();

        switch (formState.mode) {
            case MODE_LOGIN:
                login()
                // code block
                break;
            case MODE_REGISTER:
                register()
                // code block
                break;
            default:
                register() // defaulted to register
                // code block
        }
        console.log("from state", formState);
    };

    function switchMode() {
        setFormState({
            ...formState,
            mode: formState.mode === MODE_REGISTER
                ? MODE_LOGIN
                : MODE_REGISTER
        })

    };

    return (

            <form onSubmit={handleSubmit}>

Signup

                <input
                    name="username"
                    onChange={handleChange}
                    placeholder="username"
                    value={formState.username}
                    label="email"></input>
                <input
                    name="password"
                    onChange={handleChange}
                    placeholder="password"
                    value={formState.password}
                    label="password"></input>
                <input
                    name="confirmPassword"
                    onChange={handleChange}
                    placeholder="confirmPassword"
                    value={formState.confirmPassword}
                    label="password"></input>
                <button type="submit">

                        {formState.mode}

                </button>
            </form>
            <button name="login-or-register" onClick={switchMode}>

Switch to {formState.mode === MODE_REGISTER
                        ? MODE_LOGIN
                        : MODE_REGISTER}

            </button>

    )
};

export default LoginOrRegister


text:
Q: JavaScript ES6 inline object literal create logic Is there anyway to rewrite the following ES6 JavaScript to not require a temporary storage variable data?
const data = {};

if(error) {
    data.error = error;
} else {
    data.response = 'some response here';
}

res.json(200, data);

I'd like to just be able to inline the object to res.json():
res.json(200, {
    // inline logic that is identical to above
});

A: you could use ternary operator
res.json(200, error ? {error} : {response: 'some response here'});